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

/*
TODO
----

[ ] combat battle screen - splay stack / dialog for watching contents and taking hits
[ ] killed leader stash for buy/trash phase

[ ] emperor variant (and tokens)
[ ] expansion cards (and images)

*/

var game
var view
const states = {}

const P1 = "Red"
const P2 = "Blue"
const P3 = "Yellow"
const P4 = "Green"

exports.scenarios = [ "Standard" ]

exports.roles = function (scenario, options) {
	if (options.players == 2)
		return [ P1, P2 ]
	if (options.players == 3)
		return [ P1, P2, P3 ]
	return [ P1, P2, P3, P4 ]
}

// === CONSTANTS ===

const PLAYER_NAMES = [ P1, P2, P3, P4 ]

const PLAYER_INDEX = {
	[P1]: 0,
	[P2]: 1,
	[P3]: 2,
	[P4]: 3,
	"Observer": -1,
}

const MILITARY = 0
const SENATE = 1
const POPULACE = 2

const LEGION_COUNT = 33
const BARBARIAN_COUNT = [ 36, 46, 56 ]

// REGIONS

const ITALIA = 0
const ASIA = 1
const GALLIA = 2
const MACEDONIA = 3
const PANNONIA = 4
const THRACIA = 5
const BRITANNIA = 6
const GALATIA = 7
const SYRIA = 8
const AEGYPTUS = 9
const AFRICA = 10
const HISPANIA = 11

const ALAMANNI_HOMELAND = 12
const FRANKS_HOMELAND = 13
const GOTHS_HOMELAND = 14
const SASSANIDS_HOMELAND = 15
const NOMADS_HOMELAND = 16
const MARE_OCCIDENTALE = 17
const MARE_ORIENTALE = 18
const OCEANUS_ATLANTICUS = 19
const PONTUS_EUXINUS = 20
const AVAILABLE = 21
const UNAVAILABLE = 22
const ARMY = 23

const REGION_NAME = [
	"Italia",
	"Asia",
	"Gallia",
	"Macedonia",
	"Pannonia",
	"Thracia",
	"Britannia",
	"Galatia",
	"Syria",
	"Aegyptus",
	"Africa",
	"Hispania",
	"Alamanni Homeland",
	"Frank Homeland",
	"Goth Homeland",
	"Sassanid Homeland",
	"Nomad Homeland",
	"Mare Occidentale",
	"Mare Orientale",
	"Oceanus Atlanticus",
	"Pontus Euxinus",
	"Available",
	"Unavailable",
]

const ADJACENT = [
	/* ITALIA */ [ GALLIA, PANNONIA, MARE_OCCIDENTALE ],
	/* ASIA */ [ THRACIA, GALATIA, MARE_ORIENTALE, PONTUS_EUXINUS ],
	/* GALLIA */ [ ITALIA, PANNONIA, HISPANIA, FRANKS_HOMELAND, MARE_OCCIDENTALE, OCEANUS_ATLANTICUS ],
	/* MACEDONIA */ [ PANNONIA, THRACIA, MARE_OCCIDENTALE, MARE_ORIENTALE ],
	/* PANNONIA */ [ ITALIA, GALLIA, MACEDONIA, THRACIA, ALAMANNI_HOMELAND, FRANKS_HOMELAND, MARE_OCCIDENTALE ],
	/* THRACIA */ [ ASIA, MACEDONIA, PANNONIA, ALAMANNI_HOMELAND, GOTHS_HOMELAND, MARE_ORIENTALE, PONTUS_EUXINUS ],
	/* BRITANNIA */ [ OCEANUS_ATLANTICUS ],
	/* GALATIA */ [ ASIA, SYRIA, SASSANIDS_HOMELAND, MARE_ORIENTALE, PONTUS_EUXINUS ],
	/* SYRIA */ [ AEGYPTUS, GALATIA, SASSANIDS_HOMELAND, MARE_ORIENTALE ],
	/* AEGYPTUS */ [ AFRICA, SYRIA, NOMADS_HOMELAND, MARE_ORIENTALE ],
	/* AFRICA */ [ AEGYPTUS, HISPANIA, NOMADS_HOMELAND, MARE_OCCIDENTALE, MARE_ORIENTALE, OCEANUS_ATLANTICUS ],
	/* HISPANIA */ [ GALLIA, AFRICA, MARE_OCCIDENTALE, OCEANUS_ATLANTICUS ],
	/* ALAMANNI_HOMELAND */ [ PANNONIA, THRACIA, FRANKS_HOMELAND, GOTHS_HOMELAND ],
	/* FRANKS_HOMELAND */ [ GALLIA, PANNONIA, ALAMANNI_HOMELAND ],
	/* GOTHS_HOMELAND */ [ THRACIA, ALAMANNI_HOMELAND, PONTUS_EUXINUS ],
	/* SASSANIDS_HOMELAND */ [ GALATIA, SYRIA, PONTUS_EUXINUS ],
	/* NOMADS_HOMELAND */ [ AEGYPTUS, AFRICA, OCEANUS_ATLANTICUS ],
	/* MARE_OCCIDENTALE */ [ ITALIA, GALLIA, MACEDONIA, PANNONIA, AFRICA, HISPANIA, MARE_ORIENTALE, OCEANUS_ATLANTICUS ],
	/* MARE_ORIENTALE */ [ ASIA, MACEDONIA, THRACIA, AEGYPTUS, AFRICA, GALATIA, SYRIA, MARE_OCCIDENTALE ],
	/* OCEANUS_ATLANTICUS */ [ GALLIA, AFRICA, HISPANIA, BRITANNIA, NOMADS_HOMELAND, MARE_OCCIDENTALE ],
	/* PONTUS_EUXINUS */ [ ASIA, THRACIA, GALATIA, GOTHS_HOMELAND, SASSANIDS_HOMELAND ],
]

const PRETENDER_ADJACENT = [
	/* ITALIA */ [ GALLIA, PANNONIA, MARE_OCCIDENTALE ],
	/* ASIA */ [ THRACIA, GALATIA, MARE_ORIENTALE, PONTUS_EUXINUS ],
	/* GALLIA */ [ ITALIA, PANNONIA, HISPANIA, BRITANNIA, FRANKS_HOMELAND, MARE_OCCIDENTALE, OCEANUS_ATLANTICUS ],
	/* MACEDONIA */ [ PANNONIA, THRACIA, MARE_OCCIDENTALE, MARE_ORIENTALE ],
	/* PANNONIA */ [ ITALIA, GALLIA, MACEDONIA, THRACIA, ALAMANNI_HOMELAND, FRANKS_HOMELAND, MARE_OCCIDENTALE ],
	/* THRACIA */ [ ASIA, MACEDONIA, PANNONIA, ALAMANNI_HOMELAND, GOTHS_HOMELAND, MARE_ORIENTALE, PONTUS_EUXINUS ],
	/* BRITANNIA */ [ GALLIA, OCEANUS_ATLANTICUS ],
	/* GALATIA */ [ ASIA, SYRIA, SASSANIDS_HOMELAND, MARE_ORIENTALE, PONTUS_EUXINUS ],
	/* SYRIA */ [ AEGYPTUS, GALATIA, SASSANIDS_HOMELAND, MARE_ORIENTALE ],
	/* AEGYPTUS */ [ AFRICA, SYRIA, NOMADS_HOMELAND, MARE_ORIENTALE ],
	/* AFRICA */ [ AEGYPTUS, HISPANIA, NOMADS_HOMELAND, MARE_OCCIDENTALE, MARE_ORIENTALE, OCEANUS_ATLANTICUS ],
	/* HISPANIA */ [ GALLIA, AFRICA, MARE_OCCIDENTALE, OCEANUS_ATLANTICUS ],
	/* ALAMANNI_HOMELAND */ [ PANNONIA, THRACIA, FRANKS_HOMELAND, GOTHS_HOMELAND ],
	/* FRANKS_HOMELAND */ [ GALLIA, PANNONIA, ALAMANNI_HOMELAND ],
	/* GOTHS_HOMELAND */ [ THRACIA, ALAMANNI_HOMELAND, PONTUS_EUXINUS ],
	/* SASSANIDS_HOMELAND */ [ GALATIA, SYRIA, PONTUS_EUXINUS ],
	/* NOMADS_HOMELAND */ [ AEGYPTUS, AFRICA, OCEANUS_ATLANTICUS ],
	/* MARE_OCCIDENTALE */ [ ITALIA, GALLIA, MACEDONIA, PANNONIA, AFRICA, HISPANIA, MARE_ORIENTALE, OCEANUS_ATLANTICUS ],
	/* MARE_ORIENTALE */ [ ASIA, MACEDONIA, THRACIA, AEGYPTUS, AFRICA, GALATIA, SYRIA, MARE_OCCIDENTALE ],
	/* OCEANUS_ATLANTICUS */ [ GALLIA, AFRICA, HISPANIA, BRITANNIA, NOMADS_HOMELAND, MARE_OCCIDENTALE ],
	/* PONTUS_EUXINUS */ [ ASIA, THRACIA, GALATIA, GOTHS_HOMELAND, SASSANIDS_HOMELAND ],
]

// BARBARIANS

const ALAMANNI = 0
const FRANKS = 1
const GOTHS = 2
const SASSANIDS = 3
const NOMADS = 4

const first_barbarian = [ 3, 13, 23, 34, 46 ]
const last_barbarian = [ 12, 22, 33, 45, 55 ]

const POSTUMUS = 0
const PRIEST_KING = 1
const ZENOBIA = 2
const CNIVA = first_barbarian[GOTHS] + 0
const ARDASHIR = first_barbarian[SASSANIDS] + 0
const SHAPUR = first_barbarian[SASSANIDS] + 1

const CNIVA_BONUS = 1 << 3
const ARDASHIR_BONUS = 1 << 4
const SHAPUR_BONUS = 1 << 5

const RIVAL_EMPEROR_NAME = [ "Postumus", "Priest King", "Zenobia" ]

const GENERAL_NAME = [
	"Red General", "Red General", "Red General", "Red General", "Red General", "Red General",
	"Blue General", "Blue General", "Blue General", "Blue General", "Blue General", "Blue General",
	"Yellow General", "Yellow General", "Yellow General", "Yellow General", "Yellow General", "Yellow General",
	"Green General", "Green General", "Green General", "Green General", "Green General", "Green General",
]

const BARBARIAN_NAME = [
	"Alamanni",
	"Franks",
	"Goths",
	"Sassanids",
	"Nomads",
]

const BARBARIAN_HOMELAND = [
	ALAMANNI_HOMELAND,
	FRANKS_HOMELAND,
	GOTHS_HOMELAND,
	SASSANIDS_HOMELAND,
	NOMADS_HOMELAND,
]

const BARBARIAN_INVASION = [
	// Alamanni
	[
		[ 1, 3, [ PANNONIA, ITALIA ] ],
		[ 4, 6, [ THRACIA, MACEDONIA ] ],
	],
	// Franks
	[
		[ 1, 2, [ BRITANNIA, GALLIA ] ],
		[ 3, 4, [ GALLIA, HISPANIA ] ],
		[ 5, 6, [ PANNONIA, ITALIA ] ],
	],
	// Goths
	[
		[ 1, 2, [ THRACIA, MACEDONIA ] ],
		[ 3, 4, [ ASIA, MACEDONIA ] ],
		[ 5, 6, [ GALATIA, SYRIA ] ],
	],
	// Sassanids
	[
		[ 1, 3, [ GALATIA, ASIA ] ],
		[ 4, 6, [ SYRIA, AEGYPTUS ] ],
	],
	// Nomads
	[
		[ 1, 3, [ AFRICA, HISPANIA ] ],
		[ 4, 6, [ AEGYPTUS, SYRIA ] ],
	],
]

const CRISIS_TABLE_4P = [
	0,
	SASSANIDS,
	FRANKS,
	SASSANIDS,
	GOTHS,
	0,
	ALAMANNI,
	NOMADS,
	FRANKS,
	NOMADS,
	0,
]

const CRISIS_TABLE_3P = [
	0,
	FRANKS,
	SASSANIDS,
	SASSANIDS,
	FRANKS,
	0,
	ALAMANNI,
	GOTHS,
	GOTHS,
	ALAMANNI,
	0,
]

const CRISIS_TABLE_2P = [
	0,
	FRANKS,
	ALAMANNI,
	FRANKS,
	GOTHS,
	0,
	GOTHS,
	FRANKS,
	ALAMANNI,
	ALAMANNI,
	0,
]

// CARDS

const EVENT_PLAGUE_OF_CYPRIAN = 1
const EVENT_ARDASHIR = 2
const EVENT_PRIEST_KING = 3
const EVENT_PALMYRA_ALLIES = 4
const EVENT_SHAPUR_I = 5
const EVENT_POSTUMUS = 6
const EVENT_LUDI_SAECULARES = 7
const EVENT_CNIVA = 8
const EVENT_ZENOBIA = 9
const EVENT_BAD_AUGURIES = 10
const EVENT_RAIDING_PARTIES = 11
const EVENT_PREPARING_FOR_WAR = 12
const EVENT_INFLATION = 13
const EVENT_GOOD_AUGURIES = 14
const EVENT_DIOCLETIAN = 15

const EVENT_NAME = [
	"None",
	"Plague of Cyprian",
	"Ardashir",
	"Priest King",
	"Palmyra Allies",
	"Shapur I",
	"Postumus",
	"Ludi Saeculares",
	"Cniva",
	"Zenobia",
	"Bad Auguries",
	"Raiding Parties",
	"Preparing for War",
	"Inflation",
	"Good Auguries",
	"Diocletian",
]

const CARD_M1 = [ 0, 11 ]
const CARD_S1 = [ 12, 23 ]
const CARD_P1 = [ 24, 35 ]
const CARD_M2 = [ 36, 44 ]
const CARD_S2 = [ 45, 53 ]
const CARD_P2 = [ 54, 62 ]
const CARD_M2X = [ 63, 71 ]
const CARD_S2X = [ 72, 80 ]
const CARD_P2X = [ 81, 89 ]
const CARD_M3 = [ 90, 97 ]
const CARD_S3 = [ 98, 105 ]
const CARD_P3 = [ 106, 113 ]
const CARD_M3X = [ 114, 121 ]
const CARD_S3X = [ 122, 129 ]
const CARD_P3X = [ 130, 137 ]
const CARD_M4 = [ 138, 143 ]
const CARD_S4 = [ 144, 149 ]
const CARD_S4B = [ 150, 155 ]
const CARD_P4 = [ 156, 161 ]
const CARD_M4X = [ 162, 167 ]
const CARD_S4X = [ 168, 173 ]
const CARD_P4X = [ 174, 179 ]

const CARD_INDEX = [
	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3,
	3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
	7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11,
	11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15,
	15, 15, 15, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 20, 20,
	20, 20, 20, 20, 21, 21, 21, 21, 21, 21,
]

const CARD_INFO = [
	{ name: "M1", type: 0, value: 1, event: null },
	{ name: "S1", type: 1, value: 1, event: null },
	{ name: "P1", type: 2, value: 1, event: null },
	{ name: "M2", type: 0, value: 2, event: "Castra" },
	{ name: "S2", type: 1, value: 2, event: "Tribute" },
	{ name: "P2", type: 2, value: 2, event: "Quaestor" },
	{ name: "M2X", type: 0, value: 2, event: "Cavalry" },
	{ name: "S2X", type: 1, value: 2, event: "Princeps Senatus" },
	{ name: "P2X", type: 2, value: 2, event: "Ambitus" },
	{ name: "M3", type: 0, value: 3, event: "Flanking Maneuver" },
	{ name: "S3", type: 1, value: 3, event: "Foederati" },
	{ name: "P3", type: 2, value: 3, event: "Mob" },
	{ name: "M3X", type: 0, value: 3, event: "Force March" },
	{ name: "S3X", type: 1, value: 3, event: "Frumentarii" },
	{ name: "P3X", type: 2, value: 3, event: "Mobile Vulgus" },
	{ name: "M4", type: 0, value: 4, event: "Praetorian Guard" },
	{ name: "S4", type: 1, value: 4, event: "Damnatio Memoriae" },
	{ name: "S4B", type: 1, value: 4, event: "Damnatio Memoriae (exp)" },
	{ name: "P4", type: 2, value: 4, event: "Pretender" },
	{ name: "M4X", type: 0, value: 4, event: "Spiculum" },
	{ name: "S4X", type: 1, value: 4, event: "Triumph" },
	{ name: "P4X", type: 2, value: 4, event: "Demagogue" },
]

function card_name(c) {
	return CARD_INFO[CARD_INDEX[c]].name
}

function card_value(c) {
	return CARD_INFO[CARD_INDEX[c]].value
}

function card_influence(c) {
	return CARD_INFO[CARD_INDEX[c]].type
}

function card_event_name(c) {
	return CARD_INFO[CARD_INDEX[c]].event
}

const PLAY_CARD_EVENT = {
	"Castra": play_castra,
	"Tribute": play_tribute,
	"Quaestor": play_quaestor,
	"Flanking Maneuver": play_flanking_maneuver,
	"Foederati": play_foederati,
	"Mob": play_mob,
	"Praetorian Guard": play_praetorian_guard,
	"Damnatio Memoriae": play_damnatio_memoriae,
	"Damnatio Memoriae (exp)": play_damnatio_memoriae_exp,
	"Pretender": play_pretender,
}

const CAN_PLAY_CARD_EVENT = {
	"Castra": can_play_castra,
	"Tribute": can_play_tribute,
	"Quaestor": can_play_quaestor,
	"Flanking Maneuver": null,
	"Foederati": can_play_foederati,
	"Mob": can_play_mob,
	"Praetorian Guard": can_play_praetorian_guard,
	"Damnatio Memoriae": null,
	"Damnatio Memoriae (exp)": null,
	"Pretender": can_play_pretender,
}

function can_play_card_event(c) {
	let f = CAN_PLAY_CARD_EVENT[card_event_name(c)]
	return f ? f() : false
}

function play_card_event(c) {
	PLAY_CARD_EVENT[card_event_name(c)]()
}

function add_card_ip(c) {
	let value = CARD_INFO[CARD_INDEX[c]].value
	let type = CARD_INFO[CARD_INDEX[c]].type
	game.ip[type] += value
}

function is_region(where) {
	return where < AVAILABLE
}

function is_province(where) {
	return where < 12
}

function is_sea(where) {
	return where >= MARE_OCCIDENTALE && where <= PONTUS_EUXINUS
}

function current_hand() { return game.hand[game.current] }
function current_draw() { return game.draw[game.current] }
function current_discard() { return game.discard[game.current] }

function get_barbarian_tribe(id) {
	for (let tribe = 0; tribe < 5; ++tribe)
		if (id >= first_barbarian[tribe] && id <= last_barbarian[tribe])
			return tribe
	return -1
}

function is_barbarian_leader(id) {
	return id === CNIVA || id === ARDASHIR || id === SHAPUR
}

// === BOARD STATE ===

const BIT_AMPHITHEATER = 1 << 7
const BIT_BASILICA = 1 << 8
const BIT_LIMES = 1 << 9
const BIT_QUAESTOR = 1 << 10
const BIT_MILITIA = 1 << 11
const BIT_BREAKAWAY = 1 << 12
const BIT_SEAT_OF_POWER = 1 << 13
const BIT_MILITIA_CASTRA = 1 << 14

function is_no_place_governor(where) {
	return where >= game.provinces.length
}

function get_support(where) {
	return game.provinces[where] & 15
}

function set_support(where, level) {
	game.provinces[where] &= ~15
	game.provinces[where] |= level
}

function get_mobs(where) {
	return (game.provinces[where] >> 4) & 7
}

function set_mobs(where, n) {
	game.provinces[where] &= ~(7 << 4)
	game.provinces[where] |= n << 4
}

function has_quaestor(where) { return game.provinces[where] & BIT_QUAESTOR }
function add_quaestor(where) { game.provinces[where] |= BIT_QUAESTOR }
function remove_quaestor(where) { game.provinces[where] &= ~BIT_QUAESTOR }

function has_militia(where) { return game.provinces[where] & BIT_MILITIA }
function add_militia(where) { game.provinces[where] |= BIT_MILITIA }
function remove_militia(where) { game.provinces[where] &= ~BIT_MILITIA }

function has_amphitheater(where) { return game.provinces[where] & BIT_AMPHITHEATER }
function has_basilica(where) { return game.provinces[where] & BIT_BASILICA }
function has_limes(where) { return game.provinces[where] & BIT_LIMES }
function add_amphitheater(where) { game.provinces[where] |= BIT_AMPHITHEATER }
function add_basilica(where) { game.provinces[where] |= BIT_BASILICA }
function add_limes(where) { game.provinces[where] |= BIT_LIMES }

function is_breakaway(where) { return game.provinces[where] & BIT_BREAKAWAY }
function add_breakaway(where) { game.provinces[where] |= BIT_BREAKAWAY }
function remove_breakaway(where) { game.provinces[where] &= ~BIT_BREAKAWAY }

function is_seat_of_power(where) { return game.provinces[where] & BIT_SEAT_OF_POWER }
function add_seat_of_power(where) { game.provinces[where] |= BIT_SEAT_OF_POWER }
function remove_seat_of_power(where) { game.provinces[where] &= ~BIT_SEAT_OF_POWER }

function has_militia_castra(where) { return game.provinces[where] & BIT_MILITIA_CASTRA }
function add_militia_castra(where) { game.provinces[where] |= BIT_MILITIA_CASTRA }
function remove_militia_castra(where) { game.provinces[where] &= ~BIT_MILITIA_CASTRA }

function get_barbarian_location(id) { return game.barbarians[id] & 63 }
function set_barbarian_location(id, loc) { game.barbarians[id] = loc }
function is_barbarian_inactive(id) { return game.barbarians[id] & 64 }
function is_barbarian_active(id) { return !is_barbarian_inactive(id) }
function set_barbarian_inactive(id) { game.barbarians[id] |= 64 }
function set_barbarian_active(id) { game.barbarians[id] &= 63 }

function get_rival_emperor_location(id) { return game.barbarians[id] }
function set_rival_emperor_location(id, loc) { game.barbarians[id] = loc }

function get_legion_location(ix) { return game.legions[ix] & 63 }
function set_legion_location(ix, loc) { game.legions[ix] = loc }
function is_legion_reduced(ix) { return game.legions[ix] & 64 }
function set_legion_reduced(ix) { game.legions[ix] |= 64 }
function set_legion_full_strength(ix) { game.legions[ix] &= 63 }

function get_governor_location(id) { return game.governors[id] & 63 }
function set_governor_location(id, loc) { game.governors[id] = loc }
function get_general_location(id) { return game.generals[id] & 63 }

function set_general_location(id, loc) { game.generals[id] = loc }
function is_general_inside_capital(id) { return game.generals[id] & 64 }
function set_general_inside_capital(id) { game.generals[id] |= 64 }
function set_general_outside_capital(id) { game.generals[id] &= ~64 }

function has_general_castra(id) { return game.generals[id] & 128 }
function add_general_castra(id) { game.generals[id] |= 128 }
function remove_general_castra(id) { game.generals[id] &= ~128 }

// === TRANSIENT STATE ===

function has_placed_governor(province) { return game.placed & (1 << province) }
function set_placed_governor(province) { game.placed |= (1 << province) }

function has_general_battled(id) { return game.battled & (1 << id) }
function set_general_battled(id) { game.battled |= (1 << id) }
function clear_general_battled(id) { game.battled &= ~(1 << id) }

function has_militia_battled(province) { return game.mbattled & (1 << province) }
function set_militia_battled(province) { game.mbattled |= (1 << province) }
function clear_militia_battled(province) { game.mbattled &= ~(1 << province) }

// === COMPOUND STATE ===

function get_selected_region() {
	if (game.selected_governor >= 0)
		return get_governor_location(game.selected_governor)
	if (game.selected_general >= 0)
		return get_general_location(game.selected_general)
	return UNAVAILABLE
}

function for_each_general(f) {
	let n = get_player_count() * 6
	for (let id = 0; id < n; ++id)
		f(id, get_general_location(id), is_general_inside_capital(id))
}

function find_general(f) {
	let n = get_player_count() * 6
	for (let id = 0; id < n; ++id)
		if (f(id, get_general_location(id), is_general_inside_capital(id)))
			return id
	return -1
}

function find_governor(f) {
	let n = get_player_count() * 6
	for (let id = 0; id < n; ++id)
		if (f(id, get_governor_location(id)))
			return id
	return -1
}

function find_barbarian(f) {
	for (let id = 3; id < game.barbarians.length; ++id)
		if (f(id, get_barbarian_location(id), is_barbarian_active(id)))
			return id
	return -1
}

function some_general(f) {
	return find_general(f) >= 0
}

function some_barbarian(f) {
	return find_barbarian(f) >= 0
}

function next_player() {
	return (game.current + 1) % get_player_count()
}

function prev_player() {
	return (game.current + get_player_count() - 1) % get_player_count()
}

function find_unused_legion() {
	for (let ix = 0; ix < LEGION_COUNT; ++ix)
		if (get_legion_location(ix) === AVAILABLE)
			return ix
	return -1
}

function can_build_improvement(province) {
	if (get_mobs(province))
		return false
	if (has_active_barbarians(province))
		return false
	if (has_rival_emperor(province))
		return false
	if (has_enemy_general_in_capital(province))
		return false
	return true
}

function update_neutral_italia() {
	if (is_neutral_province(ITALIA)) {
		let n = 1
		for (let s = 1; s < 12; ++s)
			if (is_neutral_province(s))
				++n
		if (n > 8)
			n = 8
		set_support(ITALIA, n)
	}
}

function get_player_count() {
	return game.legacy.length
}

function get_tribe_count() {
	return get_player_count() + 1
}

function can_enter_capital(where) {
	// No Capital
	if (is_no_place_governor(where))
		return false

	// Occupied by General
	if (some_general((id, loc, cap) => loc === where && cap))
		return false

	// Occupied by opponent Militia
	if (has_militia(where)) {
		if (!is_own_province(where))
			return false
	}

	return true
}

function is_own_general(id) {
	let a = game.current * 6
	return id >= a && id < a + 6
}

function is_enemy_general(id) {
	return id >= 0 && !is_own_general(id)
}

function is_own_governor(id) {
	let a = game.current * 6
	return id >= a && id < a + 6
}

function is_enemy_governor(id) {
	return id >= 0 && !is_own_governor(id)
}

function is_capital_free_of_enemy(where) {
	return !is_enemy_general(get_capital_general(where))
}

function get_province_governor(where) {
	return find_governor((id, loc) => loc === where)
}

function get_province_player(where) {
	let gov = find_governor((id, loc) => loc === where)
	if (gov >= 0)
		return gov / 6 | 0
	return -1
}

function get_capital_general(where) {
	return find_general((id, loc, cap) => loc === where && cap)
}

function is_neutral_province(where) {
	if (is_no_place_governor(where))
		return false
	return get_province_governor(where) < 0
}

function has_active_barbarians(where) {
	return some_barbarian((id, loc, active) => loc === where && active)
}

function has_inactive_barbarians(where) {
	return some_barbarian((id, loc, active) => loc === where && !active)
}

function find_barbarian_of_tribe(where, tribe) {
	for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id)
		if (get_barbarian_location(id) === where)
			return id
	return -1
}

function find_active_barbarian_of_tribe(where, tribe) {
	for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id)
		if (get_barbarian_location(id) === where && is_barbarian_active(id))
			return id
	return -1
}

function find_active_non_leader_barbarian_of_tribe(where, tribe) {
	for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id)
		if (!is_barbarian_leader(id) && get_barbarian_location(id) === where && is_barbarian_active(id))
			return id
	return -1
}

function find_inactive_barbarian_of_tribe(where, tribe) {
	for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id)
		if (get_barbarian_location(id) === where && is_barbarian_inactive(id))
			return id
	return -1
}

function find_inactive_non_leader_barbarian_of_tribe(where, tribe) {
	for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id)
		if (!is_barbarian_leader(id) && get_barbarian_location(id) === where && is_barbarian_inactive(id))
			return id
	return -1
}

function has_rival_emperor(where) {
	for (let i = 0; i < 3; ++i)
		if (get_rival_emperor_location(i) === where)
			return true
	return false
}

function is_enemy_province(where) {
	return is_enemy_governor(get_province_governor(where))
}

function is_own_province(where) {
	return is_own_governor(get_province_governor(where))
}

function is_emperor_governor(governor) {
	let emperor = get_province_governor(ITALIA)
	if (emperor >= 0 && governor >= 0)
		return (emperor / 6 | 0) === (governor / 6 | 0)
	return false
}

function has_enemy_general_in_capital(where) {
	return is_enemy_general(get_capital_general(where))
}

function has_available_governor() {
	for (let i = 0; i < 6; ++i)
		if (get_governor_location(game.current * 6 + i) === AVAILABLE)
			return true
	return false
}

function spend_military(n) {
	game.ip[MILITARY] -= n
}

function spend_senate(n) {
	game.ip[SENATE] -= n
}

function spend_populace(n) {
	game.ip[POPULACE] -= n
}

function can_place_governor(where) {
	if (is_no_place_governor(where))
		return false
	if (is_own_province(where))
		return false
	// Recalled or already attempted to place.
	if (has_placed_governor(where))
		return false
	// Cannot Place in breakaway provinces
	if (is_breakaway(where) || is_seat_of_power(where))
		return false
	return true
}

function find_active_barbarian_at_home(tribe) {
	let home = BARBARIAN_HOMELAND[tribe]
	for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id)
		if (get_barbarian_location(id) === home && is_barbarian_active(id))
			return id
	return -1
}

function count_active_barbarians_at_home(tribe) {
	let home = BARBARIAN_HOMELAND[tribe]
	let n = 0
	for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id)
		if (get_barbarian_location(id) === home && is_barbarian_active(id))
			n += 1
	return n
}

function find_inactive_barbarian_at_home(tribe) {
	let home = BARBARIAN_HOMELAND[tribe]
	for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id)
		if (get_barbarian_location(id) === home && is_barbarian_inactive(id))
			return id
	return -1
}

function count_barbarians_in_province(tribe, where) {
	let n = 0
	for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id)
		if (get_barbarian_location(id) === where)
			n += 1
	return n
}

function count_legions_in_army(army_id) {
	let n = 0
	for (let id = 0; id < LEGION_COUNT; ++id)
		if (get_legion_location(id) === ARMY + army_id)
			++n
	return n
}

function count_own_legions() {
	let n = 0
	for (let i = 0; i < 6; ++i)
		n += count_legions_in_army(game.current * 6 + i)
	return n
}

function count_barbarians_in_army(army_id) {
	let n = 0
	for (let id = 3; id < game.barbarians.length; ++id)
		if (get_barbarian_location(id) === ARMY + army_id)
			++n
	return n
}

function find_reduced_legion_in_army(id) {
	for (let i = 0; i < LEGION_COUNT; ++i)
		if (get_legion_location(i) === ARMY + id && is_legion_reduced(i))
			return i
	return -1
}

function has_reduced_legions_in_army(id) {
	return find_reduced_legion_in_army(id) >= 0
}

function has_lone_militia(where) {
	return has_militia(where) && get_capital_general(where) < 0
}

function count_units_in_army(id) {
	let n = 0
	for (let i = 0; i < LEGION_COUNT; ++i)
		if (get_legion_location(i) === ARMY + id)
			++n
	for (let i = 3; i < game.barbarians.length; ++i)
		if (get_barbarian_location(i) === ARMY + id)
			++n
	return n
}

function is_emperor_player() {
	return is_own_province(ITALIA)
}

function is_pretender_player() {
	for (let where = 1; where < 12; ++where)
		if (is_seat_of_power(where) || is_breakaway(where))
			if (is_own_province(where))
				return true
	return false
}

function is_only_pretender_player() {
	let result = false
	for (let where = 1; where < 12; ++where)
		if (is_seat_of_power(where))
			if (is_own_province(where))
				result = true
			else
				return false
	return result
}

function count_pretender_provinces() {
	let n = 0
	for (let where = 1; where < 12; ++where)
		if (is_seat_of_power(where) || is_breakaway(where))
			++n
	return n
}

function count_own_breakaway_provinces() {
	let n = 0
	for (let where = 0; where < 12; ++where)
		if (is_own_province(where) && (is_seat_of_power(where) || is_breakaway(where)))
			++n
	return n
}

function count_own_provinces() {
	let n = 0
	for (let where = 0; where < 12; ++where)
		if (is_own_province(where))
			++n
	return n
}

function count_own_improvements() {
	let n = 0
	for (let where = 0; where < 12; ++where) {
		if (is_own_province(where)) {
			if (has_amphitheater(where))
				++n
			if (has_basilica(where))
				++n
			if (has_limes(where))
				++n
		}
	}
	return n
}

function count_own_basilicas() {
	let n = 0
	for (let where = 0; where < 12; ++where)
		if (is_own_province(where) && has_basilica(where))
			++n
	return n
}

function roll_dice(count, target) {
	let hits = 0
	while (count > 0) {
		let summary = []
		let sixes = 0
		for (let i = 0; i < count; ++i) {
			let die = roll_die()
			if (die === 6)
				sixes += 1
			if (die >= target) {
				summary.push("B" + die)
				hits += 1
			} else {
				summary.push("W" + die)
			}
		}
		logi(summary.join(" "))
		count = sixes
	}
	return hits
}

function roll_dice_no_reroll(count, target) {
	let hits = 0
	let summary = []
	for (let i = 0; i < count; ++i) {
		let die = roll_die()
		if (die >= target) {
			summary.push("B" + die)
			hits += 1
		} else {
			summary.push("W" + die)
		}
	}
	logi(summary.join(" "))
	return hits
}

function eliminate_barbarian(id) {
	let tribe = get_barbarian_tribe(id)
	if (is_barbarian_leader(id) && game.battle) {
		if (id === CNIVA) {
			log("Cniva killed!")
			game.battle.killed |= CNIVA_BONUS
		}
		if (id === ARDASHIR) {
			log("Ardashir killed!")
			game.battle.killed |= ARDASHIR_BONUS
		}
		if (id === SHAPUR) {
			log("Shapur killed!")
			game.battle.killed |= SHAPUR_BONUS
		}
		set_barbarian_location(id, AVAILABLE)
	} else {
		set_barbarian_location(id, BARBARIAN_HOMELAND[tribe])
		set_barbarian_inactive(id)
	}
}

function eliminate_rival_emperor(id) {
	if (game.battle)
		game.battle.killed |= (1 << id)
	set_rival_emperor_location(id, AVAILABLE)
}

function eliminate_militia(where) {
	remove_militia(where)
	clear_militia_battled(where)
	remove_militia_castra(where)
}

function flip_discard_to_available() {
	game.draw[game.current] = game.discard[game.current]
	game.discard[game.current] = []
}

function assign_hit_to_legion(id) {
	let army = get_legion_location(id) - ARMY
	if (is_legion_reduced(id)) {
		set_legion_location(id, AVAILABLE)
		if (count_legions_in_army(army) === 0) {
			log(GENERAL_NAME[army] + " killed!")
			set_general_location(army, AVAILABLE)
			clear_general_battled(army)
		}
	} else {
		set_legion_reduced(id)
	}
}

function is_pretender_province(where) {
	return is_breakaway(where) || is_seat_of_power(where)
}

function find_seat_of_power() {
	for (let where = 1; where < 12; ++where)
		if (is_seat_of_power(where) && is_own_province(where))
			return where
	return -1
}

function is_possible_seat_of_power(from) {
	if (is_own_province(from) && get_support(from) >= 3)
		for (let to of PRETENDER_ADJACENT[from])
			if (is_own_province(to) && get_support(to) >= 3)
				return true
	return false
}

function is_expand_pretender_province(from) {
	if (get_support(from) >= 3 && !is_pretender_province(from) && is_own_province(from))
		for (let to of PRETENDER_ADJACENT[from])
			if (is_pretender_province(to) && is_own_province(to))
				return true
	return false
}

function gen_card_event(event) {
	for (let c = event[0]; c <= event[1]; ++c)
		if (set_has(game.played, c) && !set_has(game.used, c))
			gen_action_card(c)
}

function has_card_event(event) {
	for (let c = event[0]; c <= event[1]; ++c)
		if (set_has(game.played, c) && !set_has(game.used, c))
			return true
	return false
}

// === SETUP ===

states.setup_province = {
	prompt() {
		view.prompt = "Setup: Choose a province to place your governor and general."
		view.selected_governor = game.current * 6
		view.selected_general = game.current * 6
		view.color = SENATE
		for (let where = 1; where < 12; ++where)
			if (is_neutral_province(where) && !is_no_place_governor(where))
				gen_action("capital", where)
	},
	capital(where) {
		push_undo()

		log(PLAYER_NAMES[game.current] + " started in %" + where + ".")

		set_governor_location(game.current * 6 + 0, where)

		add_militia(where)

		set_general_location(game.current * 6 + 0, where)
		set_general_inside_capital(game.current * 6 + 0)
		set_legion_location(find_unused_legion(), ARMY + game.current * 6 + 0)

		game.state = "setup_hand"
	},
}

states.setup_hand = {
	prompt() {
		view.prompt = "Setup: Draw cards."
		let hand = current_hand()
		if (hand.length < 5) {
			for (let c of current_draw())
				gen_action_card(c)
		} else {
			view.actions.done = 1
		}
	},
	card(c) {
		push_undo()
		set_delete(current_draw(), c)
		set_add(current_hand(), c)
	},
	done() {
		clear_undo()
		game.state = "setup_province"
		game.current = next_player()
		if (game.current === game.first)
			goto_start_turn()
	},
}

// === UPKEEP ===

function goto_start_turn() {
	log_h1(PLAYER_NAMES[game.current])

	game.killed = 0
	game.battled = 0
	game.mbattled = 0
	game.placed = 0

	goto_upkeep()
}

function goto_upkeep() {
	for (let i = 0; i < 6; ++i) {
		let id = game.current * 6 + i
		let where = get_governor_location(id)
		if (is_province(where)) {
			if (has_quaestor(where))
				remove_quaestor(where)
			if (has_militia_castra(where))
				remove_militia_castra(where)
		}
		if (has_general_castra(id))
			remove_general_castra(id)
	}
	goto_crisis()
}

// === CRISIS ===

function goto_crisis() {
	game.crisis = -1
	game.dice[0] = roll_die()
	game.dice[1] = roll_die()
	game.dice[2] = 0
	game.dice[3] = 0

	let sum = game.dice[0] + game.dice[1]
	let msg = "Crisis B" + game.dice[0] + " W" + game.dice[1]

	if (sum === 2) {
		log(msg + " - Ira Deorum")
		return goto_ira_deorum()
	}

	if (sum === 12) {
		log(msg + " - Pax Deorum")
		return goto_pax_deorum()
	}

	if (sum === 7) {
		log(msg + " - Event")
		return goto_crisis_event()
	}

	let tribe = 0
	if (get_player_count() === 2)
		tribe = CRISIS_TABLE_2P[sum - 2]
	else if (get_player_count() === 3)
		tribe = CRISIS_TABLE_3P[sum - 2]
	else
		tribe = CRISIS_TABLE_4P[sum - 2]

	log(msg)
	goto_barbarian_crisis(tribe)
}

// CRISIS: IRA DEORUM

function goto_ira_deorum() {
	game.count = 0
	let tribe_count = get_tribe_count()
	for (let tribe = 0; tribe < tribe_count; ++tribe)
		if (find_inactive_barbarian_at_home(tribe) >= 0)
			game.count |= (1 << tribe)

	game.state = "ira_deorum"
	if (game.count === 0)
		goto_take_actions()
}

states.ira_deorum = {
	prompt() {
		prompt("Ira Deorum: Activate one barbarian in each tribe's homeland.")
		let tribe_count = get_tribe_count()
		for (let tribe = 0; tribe < tribe_count; ++tribe)
			if (game.count & (1 << tribe))
				gen_action_barbarian(find_inactive_barbarian_at_home(tribe))
	},
	barbarian(id) {
		let tribe = get_barbarian_tribe(id)
		game.count &= ~(1 << tribe)

		set_barbarian_active(id)

		if (game.count === 0)
			goto_take_actions()
	},
}

// CRISIS: PAX DEORUM

// TODO: Skip players if game end has triggered.

function goto_pax_deorum() {
	game.count = game.current
	game.current = prev_player()
	resume_pax_deorum()
}

function resume_pax_deorum() {
	game.state = "pax_deorum"
	if (game.draw[game.current].length === 0)
		flip_discard_to_available()
}

states.pax_deorum = {
	prompt() {
		prompt("Pax Deorum: Draw one card.")
		for (let c of game.draw[game.current])
			gen_action_card(c)
	},
	card(c) {
		set_add(game.hand[game.current], c)
		set_delete(game.draw[game.current], c)
		game.state = "pax_deorum_done"
	},
}

states.pax_deorum_done = {
	prompt() {
		prompt("Pax Deorum: Done.")
		view.actions.done = 1
	},
	done() {
		if (game.current === game.count) {
			goto_take_actions()
		} else {
			game.current = prev_player()
			resume_pax_deorum()
		}
	},
}

// CRISIS: BARBARIAN INVASION

function goto_barbarian_crisis(tribe) {
	game.crisis = tribe
	if (find_inactive_barbarian_at_home(tribe) >= 0)
		game.state = "barbarian_crisis"
	else
		roll_barbarian_crisis()
}

states.barbarian_crisis = {
	prompt() {
		let tribe = game.crisis
		prompt(BARBARIAN_NAME[tribe] + ": Activate one barbarian.")
		gen_action_barbarian(find_inactive_barbarian_at_home(tribe))
	},
	barbarian(id) {
		let tribe = game.crisis
		set_barbarian_active(id)
		roll_barbarian_crisis()
	},
}

function roll_barbarian_crisis() {
	let tribe = game.crisis

	let black = game.dice[2] = roll_die()
	let white = game.dice[3] = roll_die()

	if (game.active_event === EVENT_RAIDING_PARTIES)
		black = Math.max(1, black - 2)
	if (game.active_event === EVENT_PREPARING_FOR_WAR)
		black = Math.min(6, black + 2)

	log(BARBARIAN_NAME[tribe] + " B" + black + " W" + white)

	if (black <= count_active_barbarians_at_home(tribe))
		goto_barbarian_invasion(tribe)
	else
		goto_take_actions()
}

function goto_barbarian_invasion(tribe) {
	game.count = game.dice[2]

	// Ardashir: All active Sassanids invade!
	if (tribe === SASSANIDS) {
		if (get_barbarian_location(ARDASHIR) === SASSANIDS_HOMELAND)
			game.count = count_active_barbarians_at_home(tribe)
	}

	game.state = "barbarian_invasion"
}

states.barbarian_invasion = {
	prompt() {
		let tribe = game.crisis
		prompt(BARBARIAN_NAME[tribe] + " invade!")
		gen_action_barbarian(find_active_barbarian_at_home(tribe))
	},
	barbarian(id) {
		if (invade_with_barbarian(id) || --game.count === 0)
			goto_take_actions()
	},
}

function invade_with_barbarian(id) {
	let tribe = game.crisis
	let white = game.dice[3]

	let path = null
	for (let list of BARBARIAN_INVASION[tribe])
		if (white >= list[0] && white <= list[1])
			path = list[2]

	for (let i = 0; i < path.length; ++i) {
		let n = count_barbarians_in_province(tribe, path[i])
		if (n < 3) {
			invade_with_barbarian_counter(id, path, path[i])
			return false
		}
	}

	return true
}

function barbarian_name(id) {
	if (id === CNIVA) return "Cniva"
	if (id === ARDASHIR) return "Ardashir"
	if (id === SHAPUR) return "Shapur I"
	return BARBARIAN_NAME[get_barbarian_tribe(id)]
}

function invade_with_barbarian_counter(id, path, where) {
	logi(barbarian_name(id) + " to %" + where)
	set_barbarian_location(id, where)
	for (let loc of path) {
		if (has_limes(loc))
			set_barbarian_inactive(id)
		if (loc === where)
			break
	}
}

// CRISIS: EVENT

function goto_crisis_event() {
	game.active_event = game.events.pop()

	logi(EVENT_NAME[game.active_event])

	switch (game.active_event) {
	case EVENT_ARDASHIR: return goto_crisis_barbarian_leader(ARDASHIR, SASSANIDS_HOMELAND)
	case EVENT_SHAPUR_I: return goto_crisis_barbarian_leader(SHAPUR, SASSANIDS_HOMELAND)
	case EVENT_CNIVA: return goto_crisis_barbarian_leader(CNIVA, GOTHS_HOMELAND)
	case EVENT_PRIEST_KING: return goto_crisis_rival_emperor(PRIEST_KING, SYRIA)
	case EVENT_POSTUMUS: return goto_crisis_rival_emperor(POSTUMUS, GALLIA)
	case EVENT_ZENOBIA: return goto_crisis_rival_emperor(ZENOBIA, AEGYPTUS)
	case EVENT_PALMYRA_ALLIES: return goto_palmyra_allies()
	case EVENT_LUDI_SAECULARES: return goto_ludi_saeculares()
	case EVENT_DIOCLETIAN: return goto_game_end()
	}

	goto_take_actions()
}

function get_improvement_cost() {
	if (game.active_event === EVENT_INFLATION)
		return 4
	return 3
}

function get_roman_drm() {
	if (game.active_event === EVENT_BAD_AUGURIES)
		return 1
	if (game.active_event === EVENT_GOOD_AUGURIES)
		return -1
	return 0
}

function get_plague_hits() {
	if (game.active_event === EVENT_PLAGUE_OF_CYPRIAN) {
		log("Plague B0")
		return 1
	}
	return 0
}

// CRISIS: BARBARIAN LEADER

function goto_crisis_barbarian_leader(id, where) {
	game.count = id
	game.where = where
	game.state = "crisis_barbarian_leader"
}

states.crisis_barbarian_leader = {
	prompt() {
		prompt(EVENT_NAME[game.active_event] + "!")
		gen_action_region(game.where)
	},
	region(where) {
		set_barbarian_location(game.count, where)
		goto_take_actions()
	},
}

// CRISIS: RIVAL EMPEROR

function goto_crisis_rival_emperor(id, where) {
	game.count = id
	game.where = where
	game.state = "crisis_rival_emperor"
}

states.crisis_rival_emperor = {
	prompt() {
		prompt(EVENT_NAME[game.active_event] + "!")
		gen_action_region(game.where)
	},
	region(where) {
		set_rival_emperor_location(game.count, where)
		goto_take_actions()
	},
}

// CRISIS: PALMYRA ALLIES

function goto_palmyra_allies() {
	game.count = roll_dice_no_reroll(4, 4)
	resume_palmyra_allies()
}

function resume_palmyra_allies() {
	// TODO: barbarian leaders
	if (
		(find_active_barbarian_of_tribe(SASSANIDS, GALATIA) >= 0) ||
		(find_active_barbarian_of_tribe(SASSANIDS, SYRIA) >= 0) ||
		(find_active_barbarian_of_tribe(SASSANIDS, SASSANIDS_HOMELAND) >= 0)
	)
		game.state = "palmyra_allies"
	else
		goto_take_actions()
}

states.palmyra_allies = {
	prompt() {
		prompt("Palmyra Allies: Remove " + game.count + " active Sassanids.")
		let id, where

		where = get_barbarian_location(SHAPUR)
		if (where === GALATIA || where === SYRIA || where === SASSANIDS_HOMELAND)
			gen_action_barbarian(SHAPUR)

		where = get_barbarian_location(ARDASHIR)
		if (where === GALATIA || where === SYRIA || where === SASSANIDS_HOMELAND)
			gen_action_barbarian(ARDASHIR)

		id = find_active_non_leader_barbarian_of_tribe(SASSANIDS, GALATIA)
		if (id >= 0)
			gen_action_barbarian(id)
		id = find_active_non_leader_barbarian_of_tribe(SASSANIDS, SYRIA)
		if (id >= 0)
			gen_action_barbarian(id)
		id = find_active_non_leader_barbarian_of_tribe(SASSANIDS, SASSANIDS_HOMELAND)
		if (id >= 0)
			gen_action_barbarian(id)
	},
	barbarian(id) {
		push_undo()
		eliminate_barbarian(id)
		if (--game.count === 0)
			goto_take_actions()
		else
			resume_palmyra_allies()
	},
}

// CRISIS: LUDI SAECULARES

function goto_ludi_saeculares() {
	game.count = game.current // remember current player
	let emperor = get_province_player(ITALIA)
	if (emperor >= 0) {
		game.current = emperor
		game.state = "ludi_saeculares"
	} else {
		goto_take_actions()
	}
}

states.ludi_saeculares = {
	prompt() {
		prompt("Ludi Saeculares: Discard a card to gain legacy equal to twice its value.")
		for (let c of current_hand())
			gen_action_card(c)
	},
	card(c) {
		push_undo()
		set_delete(current_hand(), c)
		set_add(current_discard(), c)
		award_legacy(game.current, "Ludi Saeculares", 2 * card_value(c))
		game.state = "ludi_saeculares_done"
	},
}

states.ludi_saeculares_done = {
	prompt() {
		prompt("Ludi Saeculares: Done.")
		view.actions.done = 1
	},
	done() {
		if (game.current !== game.count)
			clear_undo()
		game.current = game.count
		goto_take_actions()
	},
}

// === TAKE ACTIONS ===

function goto_take_actions() {
	log_br()
	game.state = "take_actions"
	game.ip = [ 0, 0, 0 ]
	game.played = []
	game.used = []

	game.placed = 0
	if (is_emperor_player())
		set_placed_governor(ITALIA)
}

states.take_actions = {
	prompt() {
		let [ mip, sip, pip ] = game.ip

		prompt(`Take Actions: ${mip} Military, ${sip} Senate, ${pip} Populace.`)

		let where = UNAVAILABLE

		if (mip + sip + pip === 0 && current_hand().length > 0)
			view.actions.play_all = 1

		view.actions.end_actions = 1

		// Play cards for IP
		for (let c of current_hand())
			gen_action_card(c)

		// Use events on played cards
		for (let c of game.played)
			if (!set_has(game.used, c) && can_play_card_event(c))
				gen_action_card(c)

		if (game.selected_governor >= 0) {
			view.color = SENATE
			view.selected_governor = game.selected_governor
			where = get_governor_location(game.selected_governor)
		}

		if (game.selected_general >= 0) {
			view.color = MILITARY
			view.selected_general = game.selected_general
			where = get_general_location(game.selected_general)
		}

		// Select Governor
		for (let i = 0; i < 6; ++i) {
			let id = game.current * 6 + i
			if (id !== game.selected_governor) {
				switch (get_governor_location(id)) {
				case UNAVAILABLE:
					if (sip >= i)
						gen_action_governor(id)
					break
				case AVAILABLE:
					if (sip >= 1)
						gen_action_governor(id)
					break
				default:
					gen_action_governor(id)
					break
				}
			}
		}

		// Select General
		for (let i = 0; i < 6; ++i) {
			let id = game.current * 6 + i
			if (id !== game.selected_general) {
				switch (get_general_location(id)) {
				case UNAVAILABLE:
					if (mip >= i)
						gen_action_general(id)
					break
				case AVAILABLE:
					if (mip >= 1)
						gen_action_general(id)
					break
				default:
					gen_action_general(id)
					break
				}
			}
		}

		// Recruit Governor
		if (game.selected_governor >= 0 && where === UNAVAILABLE) {
			view.actions.recruit_governor = 0
			if (sip >= game.selected_governor % 6)
				view.actions.recruit_governor = 1
		}

		// Recruit General
		if (game.selected_general >= 0 && where === UNAVAILABLE) {
			view.actions.recruit_general = 0
			if (mip >= game.selected_general % 6)
				view.actions.recruit_general = 1
		}

		// Place Governor
		if (game.selected_governor >= 0 && where === AVAILABLE) {
			gen_place_governor()
		}

		// Create Army
		if (game.selected_general >= 0 && where === AVAILABLE) {
			if (mip >= 1 && find_unused_legion() >= 0)
				gen_create_army()
		}

		// Governor Actions
		if (game.selected_governor >= 0 && is_province(where)) {
			view.actions.place_militia = 0
			view.actions.amphitheater = 0
			view.actions.basilica = 0
			view.actions.limes = 0

			// Recall Governor
			if (sip >= 2)
				gen_action_recall(where)

			// Increase Support Level
			let support = get_support(where)
			if (where !== ITALIA && support < 4) {
				if (pip > support)
					gen_action_support(where, support + 1)
			}

			// Place Militia
			if (!has_militia(where) && is_capital_free_of_enemy(where)) {
				if (pip >= 2)
					view.actions.place_militia = 1
			}

			// Hold Games
			if (get_mobs(where)) {
				view.actions.disperse_mob = 0
				view.actions.hold_games = 0
				if (has_lone_militia(where) && mip >= 1)
					view.actions.disperse_mob = 1
				if (pip >= 2)
					view.actions.hold_games = 1
			}

			// Build an Improvement
			if (can_build_improvement(where)) {
				if (pip >= get_improvement_cost()) {
					if (!has_amphitheater(where))
						view.actions.amphitheater = 1
					if (!has_basilica(where))
						view.actions.basilica = 1
					if (!has_limes(where))
						view.actions.limes = 1
				}
			}

			// Initiate Battle with Militia not stacked with General
			if (!has_militia_battled(where)) {
				if (has_lone_militia(where))
					gen_initiate_battle(where)
			}
		}

		// General Actions
		if (game.selected_general >= 0 && is_region(where)) {
			view.actions.disperse_mob = 0
			view.actions.train_legions = 0
			view.actions.add_legion_to_army = 0

			// Disperse Mob
			if (get_mobs(where) && is_own_province(where)) {
				if (mip >= 1)
					view.actions.disperse_mob = 1
			}

			// Train Legions
			if (has_reduced_legions_in_army(game.selected_general)) {
				if (mip >= 1)
					view.actions.train_legions = 1
			}

			// Add Legion to Army
			if (is_own_province(where)) {
				let cost = count_legions_in_army(game.selected_general) + 1
				if (mip >= cost)
					view.actions.add_legion_to_army = 1
			}

			if (!has_general_battled(game.selected_general)) {
				// Move Army
				gen_move_army()

				// Initiate Battle
				gen_initiate_battle(where)

				// Free Action: Enter/Leave Capital
				if (is_province(where)) {
					if (is_general_inside_capital(game.selected_general)) {
						view.actions.leave = 1
					} else if (can_enter_capital(where)) {
						view.actions.enter = 1
						gen_action_capital(where)
					}
				}
			}
		}

	},

	end_actions() {
		push_undo()

		// If a castra is on lone militia, but general is now in the space, move it to the general.
		for (let where = 0; where < 12; ++where) {
			if (is_own_province(where) && has_militia_castra(where)) {
				let id = get_capital_general(where)
				if (is_own_general(id)) {
					remove_militia_castra(where)
					add_general_castra(id)
				}
			}
		}

		game.selected_governor = -1
		game.selected_general = -1
		goto_support_check()
	},

	play_all() {
		push_undo()
		let hand = current_hand()
		while (hand.length > 0) {
			let c = hand[0]
			log("Played " + card_name(c) + ".")
			set_delete(hand, c)
			set_add(game.played, c)
			add_card_ip(c)
		}
	},

	card(c) {
		push_undo()
		let hand = current_hand()
		if (set_has(hand, c)) {
			log("Played " + card_name(c) + ".")
			set_delete(hand, c)
			set_add(game.played, c)
			add_card_ip(c)
		} else if (set_has(game.played, c)) {
			set_add(game.used, c)
			play_card_event(c)
		}
	},

	governor(id) {
		game.selected_governor = id
		game.selected_general = -1
	},

	general(id) {
		if (is_own_general(id)) {
			game.selected_governor = -1
			game.selected_general = id
		} else {
			push_undo()
			goto_battle_vs_general(get_general_location(game.selected_general), game.selected_general, id)
		}
	},

	recruit_governor() {
		push_undo()
		log("Recruited Governor " + (game.selected_governor % 6) + ".")
		spend_senate(game.selected_governor % 6)
		set_governor_location(game.selected_governor, AVAILABLE)
	},

	recruit_general() {
		push_undo()
		log("Recruited General " + (game.selected_general % 6) + ".")
		spend_military(game.selected_general % 6)
		set_general_location(game.selected_general, AVAILABLE)
	},

	recall() {
		push_undo()
		recall_governor()
	},

	support() {
		push_undo()
		improve_support()
	},

	place_militia() {
		push_undo()
		let where = get_governor_location(game.selected_governor)
		spend_populace(2)
		add_militia(where)
	},

	hold_games() {
		push_undo()
		let where = get_governor_location(game.selected_governor)
		log("Held Games in %" + where + ".")
		spend_populace(2)
		set_mobs(where, get_mobs(where) - 1)
	},

	amphitheater() {
		push_undo()
		spend_populace(get_improvement_cost())
		let where = get_governor_location(game.selected_governor)
		add_amphitheater(where)
		log("Built Amphitheater in %" + where + ".")
	},

	basilica() {
		push_undo()
		spend_populace(get_improvement_cost())
		let where = get_governor_location(game.selected_governor)
		add_basilica(where)
		log("Built Basilica in %" + where + ".")
	},

	limes() {
		push_undo()
		spend_populace(get_improvement_cost())
		let where = get_governor_location(game.selected_governor)
		add_limes(where)
		log("Built Limes in %" + where + ".")
	},

	add_legion_to_army() {
		push_undo()
		log("Added Legion to Army.")
		let cost = count_legions_in_army(game.selected_general) + 1
		spend_military(cost)
		set_legion_location(find_unused_legion(), ARMY + game.selected_general)
	},

	train_legions() {
		push_undo()
		log("Trained Legions.")
		spend_military(1)
		set_legion_full_strength(find_reduced_legion_in_army(game.selected_general))
	},

	enter() {
		push_undo()
		enter_capital()
	},

	leave() {
		push_undo()
		set_general_outside_capital(game.selected_general)
	},

	disperse_mob() {
		push_undo()
		let where = get_selected_region()
		let n = 0
		if (has_militia(where))
			n += 1
		if (game.selected_general >= 0)
			n += count_units_in_army(game.selected_general)
		n = Math.min(get_mobs(where), n)
		log("Disperse " + n + " Mobs in %" + where)
		set_mobs(where, get_mobs(where) - n)
		reduce_support(where)
	},

	region(where) {
		push_undo()
		if (game.selected_governor >= 0) {
			spend_senate(1)
			game.count = 1
			game.where = where
			game.state = "place_governor"
		}
		if (game.selected_general >= 0) {
			if (get_general_location(game.selected_general) === AVAILABLE)
				create_army(where)
			else
				move_army_to(game.selected_general, where)
		}
	},

	capital(where) {
		push_undo()
		if (get_general_location(game.selected_general) !== where)
			move_army_to(game.selected_general, where)
		enter_capital()
	},

	barbarian(id) {
		push_undo()
		goto_battle_vs_barbarian(get_selected_region(), game.selected_general, id)
	},

	rival_emperor(id) {
		push_undo()
		goto_battle_vs_rival_emperor(get_selected_region(), game.selected_general, id)
	},

	militia(_) {
		push_undo()
		goto_battle_vs_militia(get_selected_region(), game.selected_general)
	},
}

// FREE ACTION: ENTER PROVINCIAL CAPITAL

function enter_capital() {
	let where = get_general_location(game.selected_general)

	set_general_inside_capital(game.selected_general)

	if (is_pretender_province(where) && is_enemy_province(where)) {
		game.count = get_province_governor(where) / 6 | 0
		game.where = where
		if (is_seat_of_power(where)) {
			game.state = "occupy_seat_of_power_1"
			return
		} else {
			game.state = "occupy_breakaway"
			return
		}
	}

	if (game.battle)
		end_battle()
}

function resume_occupy_seat_of_power() {
	for (let where = 1; where < 12; ++where) {
		if (is_breakaway(where) && (get_province_governor(where) / 6 | 0) === game.count) {
			game.state = "occupy_seat_of_power_2"
			return
		}
	}
	goto_replace_pretender()
}

states.occupy_seat_of_power_1 = {
	prompt() {
		prompt("Occupy Pretender Provincial Capital: Remove seat of power marker and governor.")
		view.color = POPULACE
		gen_action_region(game.where)
	},
	region(where) {
		push_undo()
		log("Removed Seat of Power in %" + where)
		remove_seat_of_power(where)
		remove_governor(where)
		resume_occupy_seat_of_power()
	},
}

states.occupy_seat_of_power_2 = {
	prompt() {
		prompt("Occupy Pretender Provincial Capital: Remove breakaway markers.")
		view.color = POPULACE
		for (let where = 1; where < 12; ++where)
			if (is_breakaway(where) && (get_province_governor(where) / 6 | 0) === game.count)
				gen_action_region(where)
	},
	region(where) {
		push_undo()
		log("Removed Breakaway in %" + where)
		remove_breakaway(where)
		resume_occupy_seat_of_power()
	},
}

states.occupy_breakaway = {
	prompt() {
		prompt("Occupy Pretender Provincial Capital: Remove breakaway marker and governor.")
		view.color = POPULACE
		gen_action_region(game.where)
	},
	region(where) {
		push_undo()
		log("Removed Breakaway in %" + where)
		remove_breakaway(where)
		remove_governor(where)
		goto_replace_pretender()
	},
}

function goto_replace_pretender() {
	if (has_available_governor())
		game.state = "replace_pretender_governor"
	else
		game.state = "take_actions"
}

states.replace_pretender_governor = {
	prompt() {
		prompt("Occupy Pretender Provincial Capital: You may place an available governor.")
		view.selected_region = game.where
		view.color = SENATE
		for (let i = 0; i < 6; ++i) {
			let id = game.current * 6 + i
			if (get_governor_location(id) === AVAILABLE)
				gen_action_governor(id)
		}
		view.actions.pass = 1
	},
	governor(id) {
		push_undo()
		log("Placed Governor in %" + game.where)
		set_governor_location(id, game.where)
		game.state = "take_actions"
	},
	pass() {
		push_undo()
		game.state = "take_actions"
	},
}

// ACTION: IMPROVE SUPPORT

function improve_support() {
	let where = get_governor_location(game.selected_governor)
	let support = get_support(where)
	log("Built Support in %" + where + ".")
	spend_populace(support + 1)
	set_support(where, support + 1)
}

// ACTION: RECALL GOVERNOR

function recall_governor() {
	let where = get_governor_location(game.selected_governor)
	log("Recalled Governor from %" + where + ".")
	spend_senate(2)
	set_placed_governor(where)
	remove_governor(where)
}

// ACTION: PLACE GOVERNOR

function gen_place_governor() {
	let sip = game.ip[SENATE]
	if (sip >= 1) {
		for (let where = 0; where < 12; ++where)
			if (can_place_governor(where))
				gen_action_region(where)
	}
}

function reduce_support(where) {
	if (get_support(where) === 1)
		remove_governor(where)
	else
		set_support(where, get_support(where) - 1)
}

function increase_support(where) {
	set_support(where, get_support(where) + 1)
}

function remove_governor(where) {
	log("Removed Governor from %" + where)

	eliminate_militia(where)
	set_mobs(where, 0)
	remove_quaestor(where)

	// TODO: manual?
	if (is_seat_of_power(where))
		auto_remove_pretender_empire(where)
	remove_breakaway(where)

	let old_governor = get_province_governor(where)
	if (old_governor >= 0) {
		set_governor_location(old_governor, AVAILABLE)
		if (where !== ITALIA && is_emperor_governor(old_governor))
			reduce_support(ITALIA)
	}

	if (where !== ITALIA)
		set_support(where, 1)

	update_neutral_italia()
}

function place_governor(where, new_governor) {
	eliminate_militia(where)
	set_mobs(where, 0)
	remove_quaestor(where)

	let old_governor = get_province_governor(where)
	if (old_governor >= 0) {
		set_governor_location(old_governor, AVAILABLE)
		if (where !== ITALIA && is_emperor_governor(old_governor))
			reduce_support(ITALIA)
	}

	set_governor_location(new_governor, where)
	if (where === ITALIA)
		set_support(where, count_own_provinces())
	else
		set_support(where, Math.max(1, get_support(where) - 1))

	if (where !== ITALIA && is_emperor_governor(new_governor))
		increase_support(ITALIA)

	update_neutral_italia()
}

function calc_needed_votes(where, pg) {
	let n = get_support(where) * 2 // base number of votes
	let old_governor = get_province_governor(where)
	let old_player = (old_governor < 0) ? -1 : (old_governor / 6 | 0)
	// Praetorian Guard ignores units in capital
	if (!pg) {
		let army_general = get_capital_general(where)
		if (army_general >= 0) {
			let army_player = army_general / 6 | 0
			let army_size = count_units_in_army(army_general)
			if (army_player === old_player)
				n += army_size
			else if (army_player === game.current)
				n -= army_size
		}
		if (has_militia(where))
			n += 1
	}
	return Math.max(1, n)
}

states.place_governor = {
	prompt() {
		let sip = game.ip[SENATE]
		let need = calc_needed_votes(game.where, false)
		let votes = game.count
		if (game.where === ITALIA)
			votes += count_own_basilicas()
		view.color = SENATE
		view.selected_region = game.where
		view.selected_governor = game.selected_governor
		prompt(`Place Governor: ${sip} Senate. Rolling ${votes} dice. ${need} votes needed.`)
		if (sip >= 1)
			view.actions.spend_senate = 1
		else
			view.actions.spend_senate = 0
		view.actions.roll = 1
	},
	spend_senate() {
		push_undo()
		spend_senate(1)
		game.count += 1
	},
	roll() {
		roll_to_place_governor()
	},
}

states.praetorian_guard = {
	prompt() {
		let mip = game.ip[MILITARY]
		let need = calc_needed_votes(game.where, true)
		let votes = game.count
		if (game.where === ITALIA)
			votes += count_own_basilicas()
		view.color = MILITARY
		view.selected_region = game.where
		view.selected_governor = game.selected_governor
		prompt(`Praetorian Guard: ${mip} Military. Rolling ${votes} dice. ${need} votes needed.`)
		if (mip >= 1)
			view.actions.spend_military = 1
		else
			view.actions.spend_military = 0
		view.actions.roll = 1
	},
	spend_military() {
		push_undo()
		spend_military(1)
		game.count += 1
	},
	roll() {
		roll_to_place_governor()
	},
}

function roll_to_place_governor(pg) {
	let need = calc_needed_votes(game.where, pg)
	let have = 0

	set_placed_governor(game.where)

	if (game.where === ITALIA)
		game.count += count_own_basilicas()

	if (pg)
		log("Praetorian Guard in %" + game.where)
	else
		log("Place Governor in %" + game.where)

	if (is_neutral_province(game.where))
		have = roll_dice(game.count, 1)
	else if (!pg && has_quaestor(game.where))
		have = roll_dice(game.count, 3)
	else
		have = roll_dice(game.count, 2)

	if (have >= need) {
		logi("Success!")

		if (game.where === ITALIA) {
			// Remember for Damnatio Memoriae
			let old_emperor = get_province_player(ITALIA)
			if (old_emperor >= 0)
				game.count = (old_emperor << 3) | get_support(ITALIA)
			else
				game.count = 0
		}

		place_governor(game.where, game.selected_governor)

		if (game.where === ITALIA && (has_card_event(CARD_S4) || has_card_event(CARD_S4B)))
			game.state = "damnatio_memoriae"
		else
			game.state = "take_actions"
	} else {
		logi("Failed!")
		game.state = "take_actions"
	}
}

// ACTION: DAMNATIO MEMORIAE

states.damnatio_memoriae = {
	prompt() {
		prompt("Place Governor: You may play Damnatio Memoriae.")
		gen_card_event(CARD_S4)
		gen_card_event(CARD_S4B)
	},
	card(c) {
		push_undo()
		log(card_name(c))
		set_add(game.used, c)
		play_card_event(c)
	},
	pass() {
		push_undo()
		game.state = "take_actions"
	},
}

function play_damnatio_memoriae() {
	award_legacy(game.count >> 3, "Damnatio Memoriae", -get_support(ITALIA))
	game.state = "damnatio_memoriae_mobs"
	game.count = game.count & 7
}

function play_damnatio_memoriae_exp() {
	award_legacy(game.count >> 3, "Damnatio Memoriae", -get_support(ITALIA))
	game.state = "take_actions"
}

states.damnatio_memoriae_mobs = {
	prompt() {
		prompt("Damnatio Memoriae: Place " + game.count + " mobs in provinces you govern.")
		view.color = SENATE
		for (let where = 0; where < 12; ++where)
			if (is_own_province(where) && get_mobs(where) < 6)
				gen_action_region(where)
	},
	region(where) {
		push_undo()
		log("Added Mob to %" + where)
		set_mobs(where, get_mobs(where) + 1)
		if (--game.count === 0)
			game.state = "take_actions"
	},
}

// ACTION: PRAETORIAN GUARD

function can_play_praetorian_guard() {
	for (let i = 0; i < 6; ++i) {
		let id = game.current * 6 + i
		if (get_governor_location(id) === AVAILABLE)
			return game.ip[MILITARY] >= 1 && !is_emperor_player() && !has_placed_governor(ITALIA)
	}
	return false
}

function play_praetorian_guard_auto() {
	game.selected_general = -1
	if (game.selected_governor < 0 || get_governor_location(game.selected_governor) !== AVAILABLE) {
		for (let i = 0; i < 6; ++i) {
			let id = game.current * 6 + i
			if (get_governor_location(id) === AVAILABLE)
				game.selected_governor = id
		}
	}
	spend_military(1)
	game.count = 1
	game.where = ITALIA
	game.state = "praetorian_guard"
}

function play_praetorian_guard() {
	game.state = "praetorian_guard_governor"
}

states.praetorian_guard_governor = {
	prompt() {
		prompt("Praetorian Guard: Choose an available governor to place in Italia.")
		for (let i = 0; i < 6; ++i) {
			let id = game.current * 6 + i
			if (get_governor_location(id) === AVAILABLE)
				gen_action_governor(id)
		}
	},
	governor(id) {
		push_undo()
		game.selected_governor = id
		game.selected_general = -1
		game.state = "praetorian_guard_italia"
	},
}

states.praetorian_guard_italia = {
	prompt() {
		prompt("Praetorian Guard: Place governor in Italia.")
		view.color = MILITARY
		gen_action_region(ITALIA)
	},
	region(where) {
		push_undo()
		spend_military(1)
		game.count = 1
		game.where = ITALIA
		game.state = "praetorian_guard"
	},
}

// ACTION: CREATE ARMY

function gen_create_army() {
	for (let i = 0; i < 6; ++i) {
		let where = get_governor_location(game.current * 6 + i)
		if (is_province(where))
			gen_action_region(where)
	}
}

function create_army(where) {
	spend_military(1)
	log("Created Army in %" + where + ".")
	set_general_location(game.selected_general, where)
	if (can_enter_capital(where))
		set_general_inside_capital(game.selected_general)
	set_legion_location(find_unused_legion(), ARMY + game.selected_general)
	game.state = "take_actions"
}

// ACTION: MOVE ARMY

function gen_move_army() {
	let mip = game.ip[MILITARY]
	let from = get_general_location(game.selected_general)
	if (mip >= 1) {
		for (let to of ADJACENT[from]) {
			if (!is_sea(to)) {
				gen_action_region(to)
				if (can_enter_capital(to))
					gen_action_capital(to)
			} else if (mip >= 2)
				gen_action_region(to)
		}
	}
}

states.move_army_at_sea = {
	prompt() {
		let mip = game.ip[MILITARY]
		prompt("Move Army: " + mip + " Military.")
		view.color = MILITARY
		view.selected_general = game.selected_general
		gen_move_army()
	},
	region(to) {
		push_undo()
		move_army_to(game.selected_general, to)
	},
	capital(to) {
		push_undo()
		move_army_to(game.selected_general, to)
		enter_capital()
	},
}

function move_army_to(who, to) {
	log("Moved Army to %" + to + ".")

	remove_general_castra(who)

	spend_military(1)
	set_general_location(who, to)

	if (is_sea(to))
		game.state = "move_army_at_sea"
	else
		game.state = "take_actions"
}

// CARD: CASTRA

function can_play_castra() {
	for (let where = 0; where < 12; ++where)
		if (!has_militia_castra(where) && has_lone_militia(where) && is_own_province(where))
			return true
	for (let i = 0; i < 6; ++i) {
		let id = game.current * 6 + i
		if (is_region(get_general_location(id)) && !has_general_castra(id))
			return true
	}
	return false
}

function play_castra() {
	game.state = "castra"
}

states.castra = {
	prompt() {
		prompt("Castra: Select an army you command.")
		for (let where = 0; where < 12; ++where)
			if (!has_militia_castra(where) && has_lone_militia(where) && is_own_province(where))
				gen_action_militia(where)
		for (let i = 0; i < 6; ++i) {
			let id = game.current * 6 + i
			if (is_region(get_general_location(id)) && !has_general_castra(id))
				gen_action_general(id)
		}
	},
	militia(where) {
		log("Castra on militia in %" + where)
		add_militia_castra(where)
		game.state = "take_actions"
	},
	general(id) {
		push_undo()
		let where = get_general_location(id)
		log("Castra on army in %" + where)
		add_general_castra(id)
		game.state = "take_actions"
	},
}

// CARD: QUAESTOR

function can_play_quaestor() {
	for (let where = 0; where < 12; ++where)
		if (!has_quaestor(where) && !is_breakaway(where) && !is_seat_of_power(where) && is_own_province(where))
			return true
	return false
}

function play_quaestor() {
	game.state = "quaestor"
}

states.quaestor = {
	prompt() {
		prompt("Quaestor: Select a province you govern.")
		view.color = POPULACE
		for (let where = 0; where < 12; ++where)
			if (!has_quaestor(where) && !is_breakaway(where) && !is_seat_of_power(where) && is_own_province(where))
				gen_action_region(where)
	},
	region(where) {
		push_undo()
		log("Quaestor in %" + where)
		add_quaestor(where)
		game.state = "take_actions"
	}
}

// CARD: TRIBUTE

function can_play_tribute() {
	for (let where = 0; where < 12; ++where)
		if (has_active_barbarians(where))
			return true
	return false
}

function play_tribute() {
	game.state = "tribute"
}

states.tribute = {
	prompt() {
		prompt("Tribute: Flip a single tribe to their inactive side in any province.")
		let tribe_count = get_tribe_count()
		for (let where = 0; where < 12; ++where) {
			for (let tribe = 0; tribe < tribe_count; ++tribe) {
				let id = find_active_barbarian_of_tribe(where, tribe)
				if (id >= 0)
					gen_action_barbarian(id)
			}
		}
	},
	barbarian(target) {
		push_undo()
		let where = get_barbarian_location(target)
		let tribe = get_barbarian_tribe(target)
		log("Tribute " + BARBARIAN_NAME[tribe] + " in %" + where)
		for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id)
			if (get_barbarian_location(id) === where && is_barbarian_active(id))
				set_barbarian_inactive(id)
		game.state = "take_actions"
	},
}

// CARD: FOEDERATI

function can_foederati_from_region_or_adjacent(from) {
	if (can_foederati_from_region(from))
		return true
	for (let to of ADJACENT[from])
		if (can_foederati_from_region(to))
			return true
	return false
}

function can_foederati_from_region(where) {
	let tribe_count = get_tribe_count()
	for (let tribe = 0; tribe < tribe_count; ++tribe) {
		if (find_active_non_leader_barbarian_of_tribe(where, tribe) >= 0)
			return true
		if (is_province(where))
			if (find_inactive_non_leader_barbarian_of_tribe(where, tribe) >= 0)
				return true
	}
	return false
}

function gen_foederati(where) {
	let tribe_count = get_tribe_count()
	for (let tribe = 0; tribe < tribe_count; ++tribe) {
		let id = find_active_non_leader_barbarian_of_tribe(where, tribe)
		if (id >= 0)
			gen_action_barbarian(id)
		if (is_province(where)) {
			id = find_inactive_non_leader_barbarian_of_tribe(where, tribe)
			if (id >= 0)
				gen_action_barbarian(id)
		}
	}
}

function can_play_foederati() {
	for (let i = 0; i < 6; ++i) {
		let id = game.current * 6 + i
		let where = get_general_location(id)
		if (is_region(where) && can_foederati_from_region_or_adjacent(where))
			return true
		where = get_governor_location(id)
		if (is_province(where) && has_lone_militia(where) && can_foederati_from_region_or_adjacent(where))
			return true
	}
	return false
}

function play_foederati() {
	game.state = "foederati"
}

states.foederati = {
	prompt() {
		prompt("Foederati: Select an army you command...")
		for (let i = 0; i < 6; ++i) {
			let id = game.current * 6 + i
			let where = get_general_location(id)
			if (is_region(where) && can_foederati_from_region_or_adjacent(where))
				gen_action_general(id)
			where = get_governor_location(id)
			if (is_province(where) && has_lone_militia(where) && can_foederati_from_region_or_adjacent(where))
				gen_action_militia(id)
		}
	},
	general(id) {
		push_undo()
		game.count = id
		game.where = get_general_location(id)
		game.state = "foederati_general"
	},
	militia(where) {
		push_undo()
		game.count = -1
		game.where = where
		game.state = "foederati_militia"
	},
}

states.foederati_general = {
	prompt() {
		if (count_legions_in_army(game.count) > count_barbarians_in_army(game.count))
			prompt("Foederati: Recruit a barbarian.")
		else
			prompt("Foederati: Remove a barbarian.")
		view.selected_general = game.count
		gen_foederati(game.where)
		for (let to of ADJACENT[game.where])
			gen_foederati(to)
	},
	barbarian(id) {
		push_undo()
		let tribe = get_barbarian_tribe(id)
		let from = get_barbarian_location(id)
		log("Foederati " + BARBARIAN_NAME[tribe] + " from %" + from + ".")
		if (count_legions_in_army(game.count) > count_barbarians_in_army(game.count)) {
			set_barbarian_location(id, ARMY + game.count)
		} else {
			eliminate_barbarian(id)
		}
		game.state = "take_actions"
	},
}

states.foederati_militia = {
	prompt() {
		prompt("Foederati: Remove a barbarian.")
		gen_foederati(game.where)
		for (let to of ADJACENT[game.where])
			gen_foederati(to)
	},
	barbarian(id) {
		push_undo()
		let tribe = get_barbarian_tribe(id)
		let from = get_barbarian_location(id)
		log("Foederati " + BARBARIAN_NAME[tribe] + " from %" + from + ".")
		eliminate_barbarian(id)
		game.state = "take_actions"
	},
}

// CARD: MOB

function can_play_mob() {
	for (let where = 0; where < 12; ++where)
		if (!get_mobs(where) && is_enemy_province(where))
			return true
	return false
}

function play_mob() {
	game.state = "mob"
}

states.mob = {
	prompt() {
		prompt("Mob: Place a mob in a province with no mobs.")
		view.color = POPULACE
		for (let where = 0; where < 12; ++where)
			if (!get_mobs(where) && is_enemy_province(where))
				gen_action_region(where)
	},
	region(where) {
		log("Mob in %" + where)
		set_mobs(where, get_mobs(where) + 1)
		game.state = "take_actions"
	},
}

// CARD: PRETENDER

function auto_remove_pretender_empire(seat) {
	let pretender = get_province_governor(seat) / 6 | 0
	log("Removed Seat of Power in %" + seat)
	remove_seat_of_power(seat)
	for (let where = 1; where < 12; ++where) {
		if (is_breakaway(where) && (get_province_governor(where) / 6 | 0) === pretender) {
			log("Removed Breakaway in %" + where)
			remove_breakaway(where)
		}
	}
}

function can_play_pretender() {
	if (is_emperor_player())
		return false
	if (is_pretender_player())
		return false
	for (let where = 1; where < 12; ++where)
		if (is_possible_seat_of_power(where))
			return true
	return false
}

function play_pretender() {
	game.state = "pretender_seat_of_power"
}

states.pretender_seat_of_power = {
	prompt() {
		prompt("Pretender: Place your seat of power marker.")
		view.color = POPULACE
		for (let where = 0; where < 12; ++where)
			for (let where = 1; where < 12; ++where)
				if (is_possible_seat_of_power(where))
					gen_action_region(where)
	},
	region(where) {
		push_undo()
		log("Seat of Power in %" + where)
		add_seat_of_power(where)
		remove_quaestor(where) // no effect anymore
		goto_pretender_breakaway()
	},
}

function goto_pretender_breakaway() {
	let seat = find_seat_of_power()
	for (let where of PRETENDER_ADJACENT[seat]) {
		if (get_support(where) >= 3 && !is_breakaway(where) && is_own_province(where)) {
			game.state = "pretender_breakaway"
			return
		}
	}
	game.state = "take_actions"
}

states.pretender_breakaway = {
	prompt() {
		prompt("Pretender: Place breakaway markers.")
		view.color = POPULACE
		let seat = find_seat_of_power()
		for (let where of PRETENDER_ADJACENT[seat])
			if (get_support(where) >= 3 && !is_breakaway(where) && is_own_province(where))
				gen_action_region(where)
	},
	region(where) {
		push_undo()
		log("Breakaway in %" + where)
		add_breakaway(where)
		remove_quaestor(where) // no effect anymore
		goto_pretender_breakaway()
	},
}

// === COMBAT ===

function play_flanking_maneuver() {
	game.battle.flanking = 1
}

function goto_battle_vs_general(where, attacker, target) {
	log("Initiate Battle against " + GENERAL_NAME[target] + " in %" + where)
	goto_battle("general", where, attacker, target)
}

function goto_battle_vs_barbarian(where, attacker, target) {
	let tribe = get_barbarian_tribe(target)
	log("Initiate Battle against " + BARBARIAN_NAME[tribe] + " in %" + where)
	goto_battle("barbarians", where, attacker, tribe)
}

function goto_battle_vs_rival_emperor(where, attacker, target) {
	log("Initiate Battle against " + RIVAL_EMPEROR_NAME[target] + " in %" + where)
	goto_battle("rival_emperor", where, attacker, target)
}

function goto_battle_vs_militia(where, attacker) {
	log("Initiated Battle against militia in %" + where)
	goto_battle("militia", where, attacker, -1)
}

function goto_battle(type, where, attacker, target) {
	spend_military(1)
	game.where = where
	game.battle = { type, attacker, target, flanking: 0, killed: 0 }
	game.state = "battle"
	if (attacker >= 0) {
		if (is_general_inside_capital(attacker))
			remove_militia_castra(where)
		remove_general_castra(attacker)
		set_general_battled(attacker)
	} else {
		remove_militia_castra(where)
		set_militia_battled(where)
	}
}

function gen_initiate_battle(where) {
	if (game.ip[MILITARY] >= 1) {
		for_each_general((id, loc) => {
			if (loc === where && is_enemy_general(id))
				gen_action_general(id)
		})
		let tribe_count = 5
		for (let tribe = 0; tribe < tribe_count; ++tribe) {
			let id = find_active_barbarian_of_tribe(where, tribe)
			if (id >= 0)
				gen_action_barbarian(id)
			else if (is_province(where)) {
				id = find_inactive_barbarian_of_tribe(where, tribe)
				if (id >= 0)
					gen_action_barbarian(id)
			}
		}
		if (is_enemy_province(where)) {
			if (has_lone_militia(where))
				gen_action_militia(where)
		}
		for (let id = 0; id < 3; ++id)
			if (get_rival_emperor_location(id) === where)
				gen_action_rival_emperor(id)
	}
}

function format_battle_target() {
	switch (game.battle.type) {
		case "militia": return "militia"
		case "barbarians": return BARBARIAN_NAME[game.battle.target]
		case "general": return GENERAL_NAME[game.battle.target]
		case "rival_emperor": return RIVAL_EMPEROR_NAME[game.battle.target]
	}
}

states.battle = {
	prompt() {
		prompt("Initiate Battle against " + format_battle_target() + " in " + REGION_NAME[game.where] + ".")
		if (!game.battle.flanking && has_card_event(CARD_M3)) {
			view.prompt += " You may play Flanking Maneuver."
			gen_card_event(CARD_M3)
		}
		view.actions.roll = 1
	},
	card(c) {
		push_undo()
		log(card_event_name(c))
		set_add(game.used, c)
		play_card_event(c)
	},
	roll() {
		// clear_undo()
		roll_combat_dice()
		if (game.battle.flanking)
			game.state = "flanking_maneuver"
		else
			goto_assign_hits()
	},
}

function format_hits() {
	return `${game.battle.ahits} hits to attacker vs ${game.battle.dhits} hits to defender`
}

states.flanking_maneuver = {
	prompt() {
		prompt("Flanking Maneuver: " + format_hits() + ".")
		view.actions.continue = 1
		view.actions.pass = 1 // XXX
		view.actions.reroll = 1
	},
	// XXX
	pass() {
		goto_assign_hits()
	},
	continue() {
		goto_assign_hits()
	},
	reroll() {
		roll_flanking_maneuver_dice()
		goto_assign_hits()
	},
}

function roll_combat_dice() {
	game.battle.dtaken = 0
	game.battle.ataken = 0

	game.battle.dhits = roll_attacker_dice()
	log("Total " + game.battle.dhits + " hits!")

	game.battle.ahits = roll_defender_dice()
	log("Total " + game.battle.ahits + " hits!")
	log_br()
}

function roll_flanking_maneuver_dice() {
	log("Flanking Maneuver Reroll")
	game.battle.dhits = roll_defender_dice()
	log("Total " + game.battle.dhits + " hits!")
	log_br()
}

function roll_general_dice(general) {
	let army = ARMY + general
	let n = 0

	let drm = get_roman_drm()

	log(GENERAL_NAME[general])

	if (is_general_inside_capital(general) && has_militia(game.where)) {
		log("Militia")
		n += roll_dice(1, 5 + drm)
	}

	let full_strength = 0
	let reduced = 0
	for (let id = 0; id < LEGION_COUNT; ++id) {
		if (get_legion_location(id) === army) {
			if (is_legion_reduced(id))
				reduced += 1
			else
				full_strength += 1
		}
	}
	if (full_strength > 0) {
		log("Legions")
		n += roll_dice(full_strength, 3 + drm)
	}
	if (reduced > 0) {
		log("Reduced Legions")
		n += roll_dice(reduced, 5 + drm)
	}

	let barbarians = 0
	for (let id = 3; id < game.barbarians.length; ++id)
		if (get_barbarian_location(id) === army)
			barbarians += 1
	if (barbarians > 0) {
		log("Barbarians")
		n += roll_dice(barbarians, 4 + drm)
	}

	return n
}

function roll_militia_dice() {
	log("Militia")
	return roll_dice(1, 5 + get_roman_drm())
}

function roll_rival_emperor_dice() {
	log("Rival Emperor")
	return roll_dice(3, 4)
}

function roll_barbarian_dice(tribe) {
	log(BARBARIAN_NAME[tribe])
	let prov = is_province(game.where)
	let n = 0
	for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id)
		if (get_barbarian_location(id) === game.where)
			if (prov || is_barbarian_active(id))
				n += is_barbarian_leader(id) ? 2 : 1
	return roll_dice(n, 4)
}

function roll_attacker_dice() {
	log_h3("ATTACKER")

	let n = get_plague_hits()
	if (game.battle.attacker < 0)
		n += roll_militia_dice()
	else
		n += roll_general_dice(game.battle.attacker)

	if (game.battle.type === "militia" && has_militia_castra(game.where)) {
		log("Castra reduces 1 hit")
		n -= 1
	}
	if (game.battle.type === "general" && has_general_castra(game.battle.target)) {
		log("Castra reduces 1 hit")
		n -= 1
	}

	if (game.battle.type === "barbarians" && get_barbarian_location(SHAPUR) === game.where) {
		log("Shapur I reduced 1 hit")
		n -= 1
	}

	return Math.max(0, n)
}

function roll_defender_dice() {
	log_h3("DEFENDER")

	let n = get_plague_hits()
	switch (game.battle.type) {
		case "militia":
			n += roll_militia_dice()
			break
		case "rival_emperor":
			n += roll_rival_emperor_dice()
			break
		case "barbarians":
			n += roll_barbarian_dice(game.battle.target)
			break
		case "general":
			n += roll_general_dice(game.battle.target)
			break
	}

	return Math.max(0, n)
}

// COMBAT: ASSIGN HITS

function has_hits_rival_emperor(id) {
	return get_rival_emperor_location(id) !== AVAILABLE
}

function gen_hits_rival_emperor(id) {
	gen_action_rival_emperor(id)
}

function has_hits_militia() {
	return has_militia(game.where)
}

function gen_hits_militia() {
	if (has_militia(game.where))
		gen_action_militia(game.where)
}

function has_hits_barbarians(tribe) {
	let prov = is_province(game.where)
	for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id)
		if (get_barbarian_location(id) === game.where)
			if (prov || is_barbarian_active(id))
				return true
	return false
}

function gen_hits_barbarians(tribe) {
	let prov = is_province(game.where)
	for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id)
		if (get_barbarian_location(id) === game.where)
			if (prov || is_barbarian_active(id))
				gen_action_barbarian(id)
}

function has_hits_general(general) {
	let army = ARMY + general
	if (is_general_inside_capital(general) && has_militia(game.where))
		return true
	for (let id = 3; id < game.barbarians.length; ++id)
		if (get_barbarian_location(id) === army)
			return true
	for (let id = 0; id < LEGION_COUNT; ++id)
		if (get_legion_location(id) === army)
			return true
	return false
}

function gen_hits_general(general) {
	let army = ARMY + general

	let done = false

	if (is_general_inside_capital(general) && has_militia(game.where)) {
		gen_action_militia(game.where)
		done = true
	}

	if (!done) {
		for (let id = 3; id < game.barbarians.length; ++id) {
			if (get_barbarian_location(id) === army) {
				gen_action_barbarian(id)
				done = true
			}
		}
	}

	// NOTE: reduce all legions before eliminating any
	if (!done) {
		for (let id = 0; id < LEGION_COUNT; ++id) {
			if (get_legion_location(id) === army && !is_legion_reduced(id)) {
				gen_action_legion(id)
				done = true
			}
		}
	}

	if (!done) {
		for (let id = 0; id < LEGION_COUNT; ++id) {
			if (get_legion_location(id) === army && is_legion_reduced(id)) {
				gen_action_legion(id)
				done = true
			}
		}
	}
}

function has_hits_on_attacker() {
	if (game.battle.ataken < game.battle.ahits) {
		if (game.battle.attacker < 0)
			return has_hits_militia()
		else
			return has_hits_general(game.battle.attacker)
	}
	return false
}

function has_hits_on_defender() {
	if (game.battle.dtaken < game.battle.dhits) {
		switch (game.battle.type) {
			case "militia":
				return has_hits_militia()
			case "rival_emperor":
				return has_hits_rival_emperor(game.battle.target)
			case "barbarians":
				return has_hits_barbarians(game.battle.target)
			case "general":
				return has_hits_general(game.battle.target)
		}
	}
	return false
}

function goto_assign_hits() {
	goto_assign_hits_on_attacker()
}

function goto_assign_hits_on_attacker() {
	if (has_hits_on_attacker())
		game.state = "assign_hits_on_attacker"
	else
		goto_assign_hits_on_defender()
}

function goto_assign_hits_on_defender() {
	if (has_hits_on_defender())
		game.state = "assign_hits_on_defender"
	else
		goto_combat_victory()
}

states.assign_hits_on_attacker = {
	prompt() {
		prompt("Combat: " + format_hits() + " \u2013 assign " + (game.battle.ahits - game.battle.ataken) + " hits to attacker!")
		if (game.battle.attacker < 0)
			gen_hits_militia()
		else
			gen_hits_general(game.battle.attacker)
	},
	militia(where) {
		game.battle.ataken += 1
		eliminate_militia(where)
		goto_assign_hits_on_attacker()
	},
	legion(id) {
		game.battle.ataken += 1
		assign_hit_to_legion(id)
		goto_assign_hits_on_attacker()
	},
	barbarian(id) {
		game.battle.ataken += 1
		eliminate_barbarian(id)
		goto_assign_hits_on_attacker()
	},
}

states.assign_hits_on_defender = {
	prompt() {
		prompt("Combat: " + format_hits() + " \u2013 assign " + (game.battle.dhits - game.battle.dtaken) + " hits to defender!")
		switch (game.battle.type) {
			case "militia":
				gen_hits_militia()
				break
			case "rival_emperor":
				gen_hits_rival_emperor(game.battle.target)
				break
			case "barbarians":
				gen_hits_barbarians(game.battle.target)
				break
			case "general":
				gen_hits_general(game.battle.target)
				break
		}
	},
	militia(where) {
		game.battle.dtaken += 1
		eliminate_militia(where)
		goto_assign_hits_on_defender()
	},
	legion(id) {
		game.battle.dtaken += 1
		assign_hit_to_legion(id)
		goto_assign_hits_on_defender()
	},
	barbarian(id) {
		game.battle.dtaken += 1
		eliminate_barbarian(id)
		goto_assign_hits_on_defender()
	},
	rival_emperor(id) {
		game.battle.dtaken += 1
		eliminate_rival_emperor(id)
		goto_assign_hits_on_defender()
	}
}

function is_attacker_eliminated() {
	if (game.selected_general < 0)
		return !has_militia(game.where)
	else
		return get_general_location(game.selected_general) === AVAILABLE
}

function is_defender_eliminated() {
	switch (game.battle.type) {
		case "militia":
			return !has_militia(game.where)
		case "rival_emperor":
			return get_rival_emperor_location(game.battle.target) === AVAILABLE
		case "barbarians":
			if (is_province(game.where))
				return find_barbarian_of_tribe(game.where, game.battle.target) < 0
			else
				return find_active_barbarian_of_tribe(game.where, game.battle.target) < 0
		case "general":
			return get_general_location(game.battle.target) === AVAILABLE
	}
	return false
}

function goto_combat_victory() {
	let de = is_defender_eliminated()
	let ae = is_attacker_eliminated()
	if (de && ae)
		end_battle()
	else if (de || game.battle.dtaken > game.battle.ataken)
		goto_combat_victory_attacker()
	else
		goto_combat_victory_defender()
}

function award_legacy(p, reason, n) {
	if (n > 0)
		log(PLAYER_NAMES[p] + " gained " + n + " Legacy for " + reason + ".")
	if (n < 0)
		log(PLAYER_NAMES[p] + " lost " + (-n) + " Legacy for " + reason + ".")
	game.legacy[p] += n
}

function goto_combat_victory_defender() {
	game.battle.killed = 0
	if (game.battle.type === "general")
		award_legacy(game.battle.target / 6 | 0, "Victory", 2)
	if (game.battle.type === "militia")
		award_legacy(get_province_player(game.where), "Victory", 2)
	end_battle()
}

function goto_combat_victory_attacker() {
	if (game.battle.type === "barbarians") {
		award_legacy(game.current, "Victory", 2 + game.battle.dtaken)

		// Surviving Barbarians go home (to active)
		let tribe = get_barbarian_tribe(game.battle.target)
		for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id)
			if (get_barbarian_location(id) === game.battle)
				set_barbarian_location(id, BARBARIAN_HOMELAND[tribe])
	} else {
		award_legacy(game.current, "Victory", 2)
	}

	// Defending Romans must retreat into province
	if (game.battle.type === "general") {
		set_general_outside_capital(game.battle.target)
		remove_general_castra(game.battle.target)
	}

	if (can_enter_capital(game.where))
		game.state = "advance_after_combat"
	else
		end_battle()
}

states.advance_after_combat = {
	prompt() {
		prompt("Combat: You may advance into provincial capital.")
		gen_action_capital(game.where)
		view.actions.pass = 1
	},
	capital(_) {
		push_undo()
		enter_capital()
	},
	pass() {
		push_undo()
		end_battle()
	},
}

function end_battle() {
	// Deselect eliminated general...
	if (game.selected_general >= 0 && get_general_location(game.selected_general) === AVAILABLE)
		game.selected_general = -1
	if (game.battle.killed && can_free_increase_support_level(game.where)) {
		game.state = "free_increase_support_level"
		return
	}
	game.battle = null
	game.state = "take_actions"
}

function can_free_increase_support_level(where) {
	return where !== ITALIA && get_support(where) < 4 && is_own_province(where)
}

states.free_increase_support_level = {
	prompt() {
		prompt("Combat: Increase support level or save counter to reduce cost of card?")
		view.color = POPULACE
		gen_action_region(game.where)
		view.actions.save = 1
	},
	region(where) {
		push_undo()
		increase_support(where)
		game.battle = null
		game.state = "take_actions"
	},
	save() {
		push_undo()
		log("Saved for cost reduction.")
		game.killed |= game.battle.killed
		game.battle = null
		game.state = "take_actions"
	},
}

// === SUPPORT CHECK ===

function goto_support_check() {
	game.count = 0
	resume_support_check()
}

function is_any_rival_emperor_or_pretender() {
	for (let i = 0; i < 3; ++i)
		if (get_rival_emperor_location(i) !== AVAILABLE)
			return true
	for (let where = 0; where < 12; ++where)
		if (is_seat_of_power(where) && is_enemy_province(where))
			return true
	return false
}

function resume_support_check() {
	for (let where = 0; where < 12; ++where) {
		if ((game.count & (1 << where)) === 0) {
			if (is_own_province(where)) {
				if (has_active_barbarians(where) || has_rival_emperor(where) || has_enemy_general_in_capital(where)) {
					game.state = "support_check"
					return
				}
			}
		}
	}
	goto_support_check_emperor()
}

states.support_check = {
	prompt() {
		prompt("Support Check: Reduce support where active barbarians, rival emperors or opponent armies in capital.")
		view.color = POPULACE
		for (let where = 0; where < 12; ++where)
			if ((game.count & (1 << where)) === 0)
				if (is_own_province(where))
					if (has_active_barbarians(where) || has_rival_emperor(where) || has_enemy_general_in_capital(where))
						gen_action_region(where)
	},
	region(where) {
		push_undo()
		game.count |= (1 << where)
		reduce_support(where)
		resume_support_check()
	},
}

function goto_support_check_emperor() {
	if (is_emperor_player() && is_any_rival_emperor_or_pretender()) {
		game.state = "support_check_emperor"
		return
	}
	goto_support_check_mobs()
}

states.support_check_emperor = {
	prompt() {
		prompt("Support Check: Reduce support in Italia for rival emperor and/or pretender on map.")
		view.color = POPULACE
		gen_action_region(ITALIA)
	},
	region(where) {
		push_undo()
		game.count |= (1 << where)
		reduce_support(where)
		goto_support_check_mobs()
	},
}

function goto_support_check_mobs() {
	for (let where = 0; where < 12; ++where) {
		if (is_own_province(where) && get_mobs(where) >= get_support(where)) {
			game.state = "support_check_mobs"
			return
		}
	}
	goto_expand_pretender_empire()
}

states.support_check_mobs = {
	prompt() {
		prompt("Support Check: Remove governors where number of mobs exceed support.")
		view.color = POPULACE
		for (let where = 0; where < 12; ++where)
			if (is_own_province(where) && get_mobs(where) >= get_support(where))
				gen_action_region(where)
	},
	region(where) {
		push_undo()
		remove_governor(where)
		goto_support_check_mobs()
	},
}

// === EXPAND PRETENDER EMPIRE ===

function goto_expand_pretender_empire() {
	for (let where = 1; where < 12; ++where) {
		if (is_expand_pretender_province(where)) {
			game.state = "expand_pretender_empire"
			return
		}
	}
	goto_gain_legacy()
}

states.expand_pretender_empire = {
	prompt() {
		prompt("Expand Pretender Empire: Add breakaway markers.")
		view.color = POPULACE
		for (let where = 1; where < 12; ++where)
			if (is_expand_pretender_province(where))
				gen_action_region(where)
	},
	region(where) {
		push_undo()
		add_breakaway(where)
		remove_quaestor(where) // no effect anymore
		goto_expand_pretender_empire()
	},
}

// === GAIN LEGACY ===

function goto_gain_legacy() {
	log_h3("Gain Legacy")

	if (is_only_pretender_player())
		award_legacy(game.current, "Pretender", count_own_breakaway_provinces())

	if (is_emperor_player())
		goto_legitimize_claim()
	else
		goto_gain_legacy_provinces()
}

function goto_legitimize_claim() {
	if (is_pretender_player())
		game.state = "legitimize_claim"
	else
		goto_gain_legacy_emperor()
}

states.legitimize_claim = {
	prompt() {
		prompt("Gain Legacy: Remove seat of power and breakaway markers in your provinces.")
		for (let where = 1; where < 12; ++where)
			if (is_own_province(where) && is_seat_of_power(where) || is_breakaway(where))
				gen_action_region(where)
	},
	region(where) {
		push_undo()
		remove_seat_of_power(where)
		remove_breakaway(where)
		goto_legitimize_claim()
	},
}

function goto_gain_legacy_emperor() {
	award_legacy(game.current, "Emperor", Math.max(0, get_support(ITALIA) - count_pretender_provinces()))
	if (!is_any_rival_emperor_or_pretender()) {
		log(PLAYER_NAMES[game.current] + " gained Emperor Turn")
		game.emperor_turns[game.current] += 1
	}
	goto_gain_legacy_provinces()
}

function goto_gain_legacy_provinces() {
	award_legacy(game.current, "Provinces", count_own_provinces())
	award_legacy(game.current, "Improvements", count_own_improvements())

	if (is_emperor_player() && game.legacy[game.current] >= 60) {
		log_br()
		log("Game will end after this round!")
		game.end = 1
	}

	goto_buy_trash_cards()
}

// === BUY / TRASH CARDS ===

function count_political_points() {
	let pp = 0
	for (let where = 0; where < 12; ++where) {
		if (is_own_province(where)) {
			pp += get_support(where)
			pp -= get_mobs(where)
		}
	}
	return pp
}

function goto_buy_trash_cards() {
	let discard = current_discard()
	for (let c of game.played)
		set_add(discard, c)
	game.played.length = 0
	game.count = 0
	game.pp = count_political_points()

	if (game.end)
		goto_end_of_turn()
	else if (current_hand().length > 0)
		game.state = "buy_trash_discard"
	else
		game.state = "buy_trash"
}

states.buy_trash_discard = {
	prompt() {
		prompt("Buy/Trash Cards: You may discard any number of cards.")
		for (let c of current_hand())
			gen_action_card(c)
		view.actions.done = 1
	},
	card(c) {
		push_undo()
		set_delete(current_hand(), c)
		set_add(current_discard(), c)
	},
	done() {
		push_undo()
		game.state = "buy_trash"
	},
}

function find_market_with_card(c) {
	for (let m of game.market)
		if (set_has(m, c))
			return m
	return null
}

function has_military_card_bonus() {
	let military_bonus = 0
	if (game.killed & CNIVA_BONUS)
		military_bonus += 2
	if (game.killed & ARDASHIR_BONUS)
		military_bonus += 2
	if (game.killed & SHAPUR_BONUS)
		military_bonus += 2
	return military_bonus
}

function has_senate_card_bonus() {
	let senate_bonus = 0
	if (game.killed & (1 << POSTUMUS))
		senate_bonus += 2
	if (game.killed & (1 << PRIEST_KING))
		senate_bonus += 2
	if (game.killed & (1 << ZENOBIA))
		senate_bonus += 2
	return senate_bonus
}

function spend_military_card_bonus() {
	game.killed &= ~(CNIVA_BONUS | ARDASHIR_BONUS | SHAPUR_BONUS)
}

function spend_senate_card_bonus() {
	game.killed &= ~((1 << POSTUMUS) | (1 << PRIEST_KING) | (1 << ZENOBIA))
}

states.buy_trash = {
	prompt() {
		let military_bonus = has_military_card_bonus()
		let senate_bonus = has_senate_card_bonus()

		prompt("Buy/Trash Cards: " + game.pp + " political points.")
		if (military_bonus) 
			view.prompt += " First Military card is 2 cheaper."
		if (senate_bonus)
			view.prompt += " First Senate card is 2 cheaper."

		let nprov = count_own_provinces()
		if (game.pp >= 3) {
			for (let c of current_discard())
				gen_action_card(c)
		}
		for (let m of game.market) {
			if (m.length > 0) {
				let c = m[0]
				let cost = card_value(c)
				if (cost > nprov)
					cost *= 2
				cost += game.count
				if (military_bonus && card_influence(c) === MILITARY)
					cost -= 2
				if (senate_bonus && card_influence(c) === SENATE)
					cost -= 2
				if (game.pp >= cost)
					gen_action_card(c)
			}
		}
		view.actions.done = 1
	},
	card(c) {
		push_undo()
		if (set_has(current_discard(), c)) {
			log("Trashed " + card_name(c))
			set_delete(current_discard(), c)
			game.pp -= 3
		} else {
			let military_bonus = has_military_card_bonus()
			let senate_bonus = has_senate_card_bonus()

			log("Bought " + card_name(c))
			set_add(current_discard(), c)
			set_delete(find_market_with_card(c), c)

			let cost = card_value(c)
			if (cost > count_own_provinces())
				cost *= 2
			cost += game.count

			if (military_bonus && card_influence(c) === MILITARY) {
				spend_military_card_bonus()
				cost -= 2
			}
			if (senate_bonus && card_influence(c) === SENATE) {
				spend_senate_card_bonus()
				cost -= 2
			}

			game.pp -= cost
			game.count += 1
		}
	},
	done() {
		push_undo()
		goto_end_of_turn()
	},
}

// === END OF TURN ===

function goto_end_of_turn() {
	game.count = 0
	goto_grow_mobs()
}

function goto_grow_mobs() {
	for (let where = 0; where < 12; ++where) {
		if ((game.count & (1 << where)) === 0) {
			if (is_own_province(where) && get_mobs(where) && !has_amphitheater(where)) {
				game.state = "grow_mobs"
				return
			}
		}
	}
	goto_flip_inactive_barbarians()
}

states.grow_mobs = {
	prompt() {
		prompt("End of Turn: Add a mob in each province you govern with mob and no amphitheater.")
		view.color = POPULACE
		for (let where = 0; where < 12; ++where)
			if ((game.count & (1 << where)) === 0)
				if (is_own_province(where) && get_mobs(where) && !has_amphitheater(where))
					gen_action_region(where)
	},
	region(where) {
		push_undo()
		game.count |= (1 << where)
		set_mobs(where, get_mobs(where) + 1)
		goto_grow_mobs()
	},
}

function goto_flip_inactive_barbarians() {
	for (let where = 0; where < 12; ++where) {
		if (is_own_province(where) && has_inactive_barbarians(where)) {
			game.state = "flip_inactive_barbarians"
			return
		}
	}
	goto_refill_hand()
}

states.flip_inactive_barbarians = {
	prompt() {
		prompt("End of Turn: Flip all inactive barbarians in your provinces to their active side.")
		view.color = POPULACE
		let tribe_count = get_tribe_count()
		for (let where = 0; where < 12; ++where) {
			if (is_own_province(where)) {
				for (let tribe = 0; tribe < tribe_count; ++tribe) {
					let id = find_inactive_barbarian_of_tribe(where, tribe)
					if (id >= 0)
						gen_action_barbarian(id)
				}
			}
		}
	},
	barbarian(target) {
		let where = get_barbarian_location(target)
		let tribe = get_barbarian_tribe(target)
		for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id)
			if (get_barbarian_location(id) === where && is_barbarian_inactive(id))
				set_barbarian_active(id)
		goto_flip_inactive_barbarians()
	},
}

function goto_refill_hand() {
	if (game.end) {
		end_refill_hand()
		return
	}
	if (current_draw().length === 0)
		flip_discard_to_available()
	game.state = "refill_hand"
}

states.refill_hand = {
	prompt() {
		prompt("End of Turn: Draw cards.")
		let hand = current_hand()
		let draw = current_draw()
		if (hand.length < 5 && draw.length > 0) {
			for (let c of draw)
				gen_action_card(c)
		} else {
			view.actions.done = 1
		}
	},
	card(c) {
		push_undo()
		let hand = current_hand()
		let draw = current_draw()
		set_delete(draw, c)
		set_add(hand, c)
		if (draw.length === 0)
			flip_discard_to_available()
	},
	done() {
		clear_undo()
		end_refill_hand()
	}
}

function end_refill_hand() {
	game.current = next_player()
	if (game.current === game.first && game.end)
		goto_game_end()
	else
		goto_start_turn()
}

// === GAME END ===

function max_emperor_turns(cutoff) {
	let n = 0
	for (let x of game.emperor_turns)
		if (x > n && x < cutoff)
			n = x
	return n
}

function award_emperor_turns(amount, cutoff) {
	let x = max_emperor_turns(cutoff)
	if (x > 0) {
		for (let p = 0; p < get_player_count(); ++p)
			if (game.emperor_turns[p] === x)
				award_legacy(p, "Emperor Turns", amount)
	}
	return x
}

function vp_tie(p) {
	let vp = game.legacy[p] * 100000

	game.current = p
	if (is_emperor_player())
		vp += 10000
	if (is_pretender_player())
		vp += 1000
	vp += count_own_provinces() * 100
	vp += count_own_legions() * 10
	vp += random(10)

	return vp
}

function goto_game_end() {
	log_h2("Game End")

	let cutoff = award_emperor_turns(10, 1000)
	cutoff = award_emperor_turns(6, cutoff)
	cutoff = award_emperor_turns(3, cutoff)
	award_emperor_turns(0, cutoff)

	let victor = game.legacy.map((legacy,p) => [vp_tie(p),p]).sort((a,b) => b[0] - a[0])[0][1]

	goto_game_over(PLAYER_NAMES[victor], PLAYER_NAMES[victor] + " won!")
}

function goto_game_over(result, victory) {
	game.state = "game_over"
	game.active = "None"
	game.result = result
	game.victory = victory
	log_br()
	log(game.victory)
	return true
}

states.game_over = {
	get inactive() {
		return game.victory
	},
	prompt() {
		view.prompt = game.victory
	},
}

// === SETUP ===

function setup_player_deck(player) {
	return [
		CARD_M1[0] + (player * 3) + 0,
		CARD_M1[0] + (player * 3) + 1,
		CARD_M1[0] + (player * 3) + 2,
		CARD_S1[0] + (player * 3) + 0,
		CARD_S1[0] + (player * 3) + 1,
		CARD_S1[0] + (player * 3) + 2,
		CARD_P1[0] + (player * 3) + 0,
		CARD_P1[0] + (player * 3) + 1,
		CARD_P1[0] + (player * 3) + 2,
	]
}

function setup_events() {
	let deck = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ]
	shuffle(deck)
	// Shuffle Diocletian with last 3 cards
	array_insert(deck, random(4), 15)
	return deck
}

function setup_market_pile(cards) {
	let pile = []
	for (let c = cards[0]; c <= cards[1]; ++c)
		pile.push(c)
	return pile
}

function setup_barbarians(tribe, home) {
	for (let id = first_barbarian[tribe]; id <= last_barbarian[tribe]; ++id) {
		if (is_barbarian_leader(id)) {
			set_barbarian_location(id, AVAILABLE)
		} else {
			set_barbarian_location(id, home)
			set_barbarian_inactive(id)
		}
	}
}

exports.setup = function (seed, scenario, options) {
	let player_count = options.players || 4

	game = {
		seed: seed,
		log: [],
		undo: [],
		active: 0,
		current: 0,
		state: "setup_province",
		first: 0,
		events: null,
		active_event: 0,

		ip: [],
		pp: 0,
		selected_governor: -1,
		selected_general: -1,
		played: [],
		used: [],
		killed: 0,
		placed: 0,
		battled: 0,
		mbattled: 0,
		count: 0,
		where: 0,
		battle: null,

		provinces: new Array(3 * player_count).fill(1),
		governors: new Array(6 * player_count).fill(UNAVAILABLE),
		generals: new Array(6 * player_count).fill(UNAVAILABLE),
		legions: new Array(LEGION_COUNT).fill(AVAILABLE),
		barbarians: new Array(BARBARIAN_COUNT[player_count - 2]).fill(AVAILABLE),

		crisis: 0,
		dice: [ 0, 0, 0, 0 ], // first two are crisis table dice, second two are barbarian homeland dice
		market: null,

		// per-player data
		legacy: new Array(player_count).fill(0),
		emperor_turns: new Array(player_count).fill(0),
		hand: [],
		draw: [],
		discard: [],
	}

	game.events = setup_events()

	game.market = [
		setup_market_pile(CARD_M2),
		setup_market_pile(CARD_S2),
		setup_market_pile(CARD_P2),
		setup_market_pile(CARD_M3),
		setup_market_pile(CARD_S3),
		setup_market_pile(CARD_P3),
		setup_market_pile(CARD_M4),
		setup_market_pile(CARD_S4),
		setup_market_pile(CARD_P4),
	]

	set_rival_emperor_location(POSTUMUS, AVAILABLE)
	set_rival_emperor_location(PRIEST_KING, AVAILABLE)
	set_rival_emperor_location(ZENOBIA, AVAILABLE)

	setup_barbarians(ALAMANNI, ALAMANNI_HOMELAND)
	setup_barbarians(FRANKS, FRANKS_HOMELAND)
	setup_barbarians(GOTHS, GOTHS_HOMELAND)
	if (player_count >= 3)
		setup_barbarians(SASSANIDS, SASSANIDS_HOMELAND)
	if (player_count >= 4)
		setup_barbarians(NOMADS, NOMADS_HOMELAND)

	for (let player = 0; player < player_count; ++player) {
		game.hand[player] = []
		game.draw[player] = setup_player_deck(player)
		game.discard[player] = []
	}

	update_neutral_italia()

	game.first = game.current = random(player_count)

	return save_game()
}

function load_game(state) {
	game = state
}

function save_game() {
	game.active = PLAYER_NAMES[game.current]
	return game
}

exports.action = function (state, player, action, arg) {
	load_game(state)
	let S = states[game.state]
	if (action in S) {
		S[action](arg)
	} else {
		if (action === "undo" && game.undo && game.undo.length > 0)
			pop_undo()
		else
			throw new Error("Invalid action: " + action)
	}
	return save_game()
}

exports.view = function (state, player_name) {
	load_game(state)

	let player = PLAYER_INDEX[player_name]
	let player_count = get_player_count()

	view = {
		log: game.log,
		current: game.current,
		prompt: null,

		provinces: game.provinces,
		governors: game.governors,
		generals: game.generals,
		legions: game.legions,
		barbarians: game.barbarians,

		first: game.first,
		crisis: game.crisis,
		dice: game.dice,
		event: game.active_event,
		market: game.market.map(m => m[0] | 0),

		played: game.played,
		used: game.used,

		legacy: game.legacy,
		emperor_turns: game.emperor_turns,
	}

	if (game.state === "game_over") {
		view.prompt = game.victory
	} else if (game.current !== player) {
		let inactive = states[game.state].inactive || game.state
		view.prompt = `Waiting for ${PLAYER_NAMES[game.current]} \u2014 ${inactive}...`
	} else {
		view.actions = {}
		states[game.state].prompt()
		if (game.undo && game.undo.length > 0)
			view.actions.undo = 1
		else
			view.actions.undo = 0
	}

	if (player >= 0 && player < player_count) {
		view.hand = game.hand[player]
		view.draw = game.draw[player]
		view.discard = game.discard[player]
	}

	save_game()
	return view
}

// === MISC ===

function prompt(s) {
	view.prompt = s
}

function log(msg) {
	game.log.push(msg)
}

function log_br() {
	if (game.log.length > 0 && game.log[game.log.length - 1] !== "")
		game.log.push("")
}

function log_h1(msg) {
	log_br()
	log(".h1 " + msg)
	log_br()
}

function log_h2(msg) {
	log_br()
	log(".h2 " + msg)
	log_br()
}

function log_h3(msg) {
	log_br()
	log(".h3 " + msg)
}

function logi(msg) {
	game.log.push(">" + msg)
}

// === COMMON LIBRARY ===

function roll_die() {
	return random(6) + 1
}

function gen_action(action, argument) {
	if (!(action in view.actions))
		view.actions[action] = []
	set_add(view.actions[action], argument)
}

function gen_action_general(id) {
	gen_action("general", id)
}

function gen_action_governor(id) {
	gen_action("governor", id)
}

function gen_action_legion(id) {
	gen_action("legion", id)
}

function gen_action_barbarian(id) {
	gen_action("barbarian", id)
}

function gen_action_rival_emperor(id) {
	gen_action("rival_emperor", id)
}

function gen_action_militia(where) {
	gen_action("militia", where)
}

function gen_action_region(where) {
	gen_action("region", where)
}

function gen_action_capital(where) {
	gen_action("capital", where)
}

function gen_action_recall(where) {
	gen_action("recall", where)
}

function gen_action_support(where, level) {
	gen_action("support", where << 3 | level)
}

function gen_action_card(c) {
	gen_action("card", c)
}

function clear_undo() {
	if (game.undo.length > 0)
		game.undo = []
}

function push_undo() {
	let copy = {}
	for (let k in game) {
		let v = game[k]
		if (k === "undo")
			continue
		else if (k === "log")
			v = v.length
		else if (typeof v === "object" && v !== null)
			v = object_copy(v)
		copy[k] = v
	}
	game.undo.push(copy)
}

function pop_undo() {
	let save_log = game.log
	let save_undo = game.undo
	game = save_undo.pop()
	save_log.length = game.log
	game.log = save_log
	game.undo = save_undo
}

function random(range) {
	// An MLCG using integer arithmetic with doubles.
	// https://www.ams.org/journals/mcom/1999-68-225/S0025-5718-99-00996-5/S0025-5718-99-00996-5.pdf
	// m = 2**35 − 31
	return (game.seed = game.seed * 200105 % 34359738337) % range
}

function shuffle(list) {
	// Fisher-Yates shuffle
	for (let i = list.length - 1; i > 0; --i) {
		let j = random(i + 1)
		let tmp = list[j]
		list[j] = list[i]
		list[i] = tmp
	}
}

// Fast deep copy for objects without cycles
function object_copy(original) {
	if (Array.isArray(original)) {
		let n = original.length
		let copy = new Array(n)
		for (let i = 0; i < n; ++i) {
			let v = original[i]
			if (typeof v === "object" && v !== null)
				copy[i] = object_copy(v)
			else
				copy[i] = v
		}
		return copy
	} else {
		let copy = {}
		for (let i in original) {
			let v = original[i]
			if (typeof v === "object" && v !== null)
				copy[i] = object_copy(v)
			else
				copy[i] = v
		}
		return copy
	}
}

// Array remove and insert (faster than splice)

function array_remove(array, index) {
	let n = array.length
	for (let i = index + 1; i < n; ++i)
		array[i - 1] = array[i]
	array.length = n - 1
}

function array_insert(array, index, item) {
	for (let i = array.length; i > index; --i)
		array[i] = array[i - 1]
	array[index] = item
}

// Set as plain sorted array

function set_has(set, item) {
	let a = 0
	let b = set.length - 1
	while (a <= b) {
		let m = (a + b) >> 1
		let x = set[m]
		if (item < x)
			b = m - 1
		else if (item > x)
			a = m + 1
		else
			return true
	}
	return false
}

function set_add(set, item) {
	let a = 0
	let b = set.length - 1
	while (a <= b) {
		let m = (a + b) >> 1
		let x = set[m]
		if (item < x)
			b = m - 1
		else if (item > x)
			a = m + 1
		else
			return
	}
	array_insert(set, a, item)
}

function set_delete(set, item) {
	let a = 0
	let b = set.length - 1
	while (a <= b) {
		let m = (a + b) >> 1
		let x = set[m]
		if (item < x)
			b = m - 1
		else if (item > x)
			a = m + 1
		else {
			array_remove(set, m)
			return
		}
	}
}