summaryrefslogtreecommitdiff
path: root/rules.js
blob: af0c0ace393720e9589cfb441e43d3d24288fd03 (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
"use strict"

// TODO: execute enemy heirs during supply phase
// TODO: reuse supply and goes-home states for pretender and king

// TODO: mulligan rule

exports.scenarios = [
	"Wars of the Roses",
	"Kingmaker",
	"Richard III",
]

exports.roles = [ "York", "Lancaster" ]

const { CARDS, BLOCKS, AREAS, BORDERS, block_index, area_index } = require('./data')

const first_area = 6 // first real area (skip pools and seas)
const last_area = AREAS.length - 4 // skip layout areas at end

const block_count = BLOCKS.length

// roles
const LANCASTER = "Lancaster"
const YORK = "York"
const ENEMY = { Lancaster: "York", York: "Lancaster" }
const OBSERVER = "Observer"
const BOTH = "Both"

const PLAYER_ID = { "": 0, Lancaster: 1, York: 2 }
const ID_PLAYER = [ "", "Lancaster", "York" ]

// areas
const NOWHERE = 0
const POOL = 1
const MINOR = 2

const IRISH_SEA = area_index["Irish Sea"]
const NORTH_SEA = area_index["North Sea"]
const ENGLISH_CHANNEL = area_index["English Channel"]

const IRELAND = area_index["Ireland"]
const SCOTLAND = area_index["Scotland"]
const FRANCE = area_index["France"]
const CALAIS = area_index["Calais"]

const CAERNARVON = area_index["Caernarvon"]
const PEMBROKE = area_index["Pembroke"]
const POWYS = area_index["Powys"]
const GLAMORGAN = area_index["Glamorgan"]

const CORNWALL = area_index["Cornwall"]
const EAST_YORKS = area_index["East Yorks"]
const HEREFORD = area_index["Hereford"]
const ISLE_OF_MAN = area_index["Isle of Man"]
const MIDDLESEX = area_index["Middlesex"]
const NORTH_YORKS = area_index["North Yorks"]
const RUTLAND = area_index["Rutland"]
const SOUTH_YORKS = area_index["South Yorks"]

// blocks
const NOBODY = -1
const B_YORK = block_index["York"]
const B_MARCH = block_index["March"]
const B_RUTLAND = block_index["Rutland"]
const B_CLARENCE_Y = block_index["Clarence/Y"]
const B_GLOUCESTER = block_index["Gloucester"]
const B_EXETER_Y = block_index["Exeter/Y"]
const B_WARWICK_Y = block_index["Warwick/Y"]
const B_KENT_Y = block_index["Kent/Y"]
const B_SALISBURY_Y = block_index["Salisbury/Y"]
const B_IRISH_MERCENARY = block_index["Irish Mercenary"]
const B_BURGUNDIAN_MERCENARY = block_index["Burgundian Mercenary"]
const B_CALAIS_MERCENARY = block_index["Calais Mercenary"]
const B_HENRY_VI = block_index["Henry VI"]
const B_PRINCE_EDWARD = block_index["Prince Edward"]
const B_EXETER_L = block_index["Exeter/L"]
const B_SOMERSET = block_index["Somerset"]
const B_RICHMOND = block_index["Richmond"]
const B_WARWICK_L = block_index["Warwick/L"]
const B_KENT_L = block_index["Kent/L"]
const B_SALISBURY_L = block_index["Salisbury/L"]
const B_CLARENCE_L = block_index["Clarence/L"]
const B_SCOTS_MERCENARY = block_index["Scots Mercenary"]
const B_WELSH_MERCENARY = block_index["Welsh Mercenary"]
const B_FRENCH_MERCENARY = block_index["French Mercenary"]
const B_REBEL = block_index["Rebel"]

// serif cirled numbers
const DIE_HIT = [ 0, '\u2776', '\u2777', '\u2778', '\u2779', '\u277A', '\u277B' ]
const DIE_MISS = [ 0, '\u2460', '\u2461', '\u2462', '\u2463', '\u2464', '\u2465' ]

const ATTACK_MARK = "*"
const RESERVE_MARK = ""

let states = {}

let game = null

function random(n) {
	if (game.rng === 1)
		return Math.floor(((game.seed = game.seed * 48271 % 0x7fffffff) / 0x7fffffff) * n)
	return (game.seed = game.seed * 200105 % 34359738337) % n
}

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

function log_battle(s) {
	game.log.push(game.active[0] + ": " + s)
}

function logp(s) {
	game.log.push(game.active + " " + s)
}

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

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

function log_move_start(from) {
	game.turn_buf = [ "#" + from ]
}

function log_move_continue(to, mark) {
	if (mark)
		game.turn_buf.push("#" + to + mark)
	else
		game.turn_buf.push("#" + to)
}

function log_move_end() {
	if (game.turn_buf) {
		game.turn_log.push(game.turn_buf)
		delete game.turn_buf
	}
}

function print_turn_log_no_count(text) {
	log(text)
	if (game.turn_log.length > 0) {
		game.turn_log.sort()
		for (let entry of game.turn_log)
			logi(entry.join(" \u2192 "))
	} else {
		logi("nothing.")
	}
	delete game.turn_log
}

function print_turn_log(text) {
	function print_move(last) {
		logi(n + " " + last.join(" \u2192 "))
	}
	game.turn_log.sort()
	let last = game.turn_log[0]
	log(text)
	let n = 0
	for (let entry of game.turn_log) {
		if (entry.toString() !== last.toString()) {
			print_move(last)
			n = 0
		}
		++n
		last = entry
	}
	if (n > 0)
		print_move(last)
	else
		logi("nothing.")
	delete game.turn_log
}

function is_inactive_player(current) {
	return current === OBSERVER || (game.active !== current && game.active !== BOTH)
}

function remove_from_array(array, item) {
	let i = array.indexOf(item)
	if (i >= 0)
		array.splice(i, 1)
}

function gen_action_undo(view) {
	if (!view.actions)
		view.actions = {}
	if (game.undo && game.undo.length > 0)
		view.actions.undo = 1
	else
		view.actions.undo = 0
}

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

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

function shuffle_deck() {
	let deck = []
	for (let c = 1; c <= 25; ++c)
		deck.push(c)
	return deck
}

function deal_cards(deck, n) {
	let hand = []
	for (let i = 0; i < n; ++i) {
		let k = random(deck.length)
		hand.push(deck[k])
		deck.splice(k, 1)
	}
	return hand
}

function count_ap(hand) {
	let count = 0
	for (let c of hand)
		count += CARDS[c].actions
	return count
}

function is_pretender_heir(who) {
	return (block_owner(who) === block_owner(game.pretender) && block_type(who) === 'heir')
}

function is_royal_heir(who) {
	return (block_owner(who) === block_owner(game.king) && block_type(who) === 'heir')
}

function is_dead(who) {
	return game.location[who] === NOWHERE
}

function is_shield_area_for(where, who, combat) {
	let haystack = AREAS[where].shields
	let needle = BLOCKS[who].shield

	// Nevilles going to exile in Calais
	if (where === CALAIS) {
		if (who === B_WARWICK_L || who === B_KENT_L || who === B_SALISBURY_L)
			return false
		if (count_blocks_exclude_mercenaries(CALAIS) < 4) {
			if (who === B_KENT_Y)
				return is_area_friendly_to(EAST_YORKS, LANCASTER)
			if (who === B_SALISBURY_Y)
				return is_area_friendly_to(NORTH_YORKS, LANCASTER)
		}
	}

	// Exeter and Clarence as enemy nobles
	if (who === B_EXETER_Y)
		return where === CORNWALL
	if (who === B_CLARENCE_L)
		return (where === SOUTH_YORKS || where === RUTLAND || where === HEREFORD)

	// Everyone can always use their own shield
	if (haystack && haystack.includes(needle))
		return true

	// Nevilles can use each other's shields if their owner is dead
	if (is_neville(who)) {
		if (is_dead(B_WARWICK_L) && is_dead(B_WARWICK_Y) && haystack.includes("Warwick"))
			return true
		if (is_dead(B_KENT_L) && is_dead(B_KENT_Y) && haystack.includes("Kent"))
			return true
		if (is_dead(B_SALISBURY_L) && is_dead(B_SALISBURY_Y) && haystack.includes("Salisbury"))
			return true
	}

	// York heirs can use any York shield
	if (is_heir(who) && block_owner(who) === YORK) {
		if (haystack.includes("York"))
			return !combat || find_senior_heir_in_area(YORK, where) === who
	}

	// Lancaster heirs can use each other's specific shields if their owner is dead
	if (is_heir(who) && block_owner(who) === LANCASTER) {
		let available = false
		if (haystack.includes("Lancaster"))
			available = true
		if (is_dead(B_EXETER_L) && is_dead(B_EXETER_Y) && haystack.includes("Exeter"))
			available = true
		if (is_dead(B_SOMERSET) && haystack.includes("Somerset"))
			available = true
		if (is_dead(B_RICHMOND) && haystack.includes("Richmond"))
			available = true
		if (available)
			return !combat || find_senior_heir_in_area(LANCASTER, where) === who
	}

	return false
}

function is_at_home(who) {
	let where = game.location[who]
	if (where === NOWHERE || where === MINOR || where === POOL)
		return true
	if (is_pretender_heir(who))
		return is_exile_area(where)
	if (is_royal_heir(who))
		return is_shield_area_for(where, who, false) || is_crown_area(where)
	if (block_type(who) === 'nobles')
		return is_shield_area_for(where, who, false)
	if (block_type(who) === 'church')
		return has_cathedral(where) === block_home(who)
	return true
}

function is_in_exile(who) {
	return is_exile_area(game.location[who])
}

function is_home_for(where, who) {
	if (is_pretender_heir(who))
		return is_shield_area_for(where, who, false)
	if (is_royal_heir(who))
		return is_crown_area(where) || is_shield_area_for(where, who, false)
	if (block_type(who) === 'nobles')
		return is_shield_area_for(where, who, false)
	if (block_type(who) === 'church')
		return block_home(who) === has_cathedral(where)
	return false
}

function is_available_home_for(where, who) {
	if (who === B_CLARENCE_L)
		return is_home_for(where, who) && is_vacant_area(where)
	return is_home_for(where, who) && is_friendly_or_vacant_area(where)
}

function count_available_homes(who) {
	let count = 0
	for (let where = first_area; where <= last_area; ++where)
		if (is_available_home_for(where, who))
			++count
	return count
}

function available_home(who) {
	for (let where = first_area; where <= last_area; ++where)
		if (is_available_home_for(where, who))
			return where
}

function pretender_go_home_if_possible(who) {
	if (!is_in_exile(who)) {
		// pretender heirs must go home!
		if (is_heir(who))
			return true
		let n = count_available_homes(who)
		if (n === 0) {
			game.turn_log.push([block_name(who), "Pool"])
			disband(who)
		} else if (n === 1) {
			let home = available_home(who)
			if (game.location[who] !== home) {
				game.location[who] = home
				game.turn_log.push([block_name(who), "#" + game.location[who]]) // TODO: "Home"?
			}
		} else {
			return true
		}
	}
	return false
}

function king_go_home_if_possible(who) {
	if (!is_in_exile(who)) {
		let n = count_available_homes(who)
		if (n === 0) {
			game.turn_log.push([block_name(who), "Pool"])
			disband(who)
		} else if (n === 1) {
			let home = available_home(who)
			if (game.location[who] !== home) {
				game.location[who] = home
				game.turn_log.push([block_name(who), "#" + game.location[who]]) // TODO: "Home"?
			}
		} else {
			return true
		}
	}
	return false
}

function is_on_map_not_in_exile_or_man(who) {
	let where = game.location[who]
	return where !== NOWHERE && where !== MINOR && where !== POOL &&
		where !== ISLE_OF_MAN && !is_exile_area(where)
}

function is_land_area(where) {
	return where !== NOWHERE && where !== MINOR && where !== POOL && !is_sea_area(where)
}

function is_area_friendly_to(where, owner) {
	let save_active = game.active
	game.active = owner
	let result = is_friendly_area(where)
	game.active = save_active
	return result
}

function is_london_friendly_to(owner) {
	return is_area_friendly_to(MIDDLESEX, owner)
}

function count_lancaster_nobles_and_heirs() {
	let count = 0
	for (let b = 0; b < block_count; ++b)
		if (block_owner(b) === LANCASTER &&
			(block_type(b) === 'nobles' || block_type(b) === 'church' || block_type(b) === 'heir'))
			if (is_on_map_not_in_exile_or_man(b))
				++count
	if (is_london_friendly_to(LANCASTER))
		++count
	return count
}

function count_york_nobles_and_heirs() {
	let count = 0
	for (let b = 0; b < block_count; ++b)
		if (block_owner(b) === YORK &&
			(block_type(b) === 'nobles' || block_type(b) === 'church' || block_type(b) === 'heir'))
			if (is_on_map_not_in_exile_or_man(b))
				++count
	if (is_london_friendly_to(YORK))
		++count
	return count
}

function block_name(who) {
	return BLOCKS[who].name
}

function block_type(who) {
	return BLOCKS[who].type
}

function block_home(who) {
	return BLOCKS[who].home
}

function block_owner(who) {
	if (who === B_REBEL) {
		if (game.pretender !== NOBODY)
			return block_owner(game.pretender)
		else if (game.king !== NOBODY)
			return ENEMY[block_owner(game.king)]
		else
			return YORK // whatever... they're both dead
	}
	return BLOCKS[who].owner
}

function block_initiative(who) {
	if (block_type(who) === 'bombard')
		return game.battle_round <= 1 ? 'A' : 'D'
	return BLOCKS[who].initiative
}

function block_printed_fire_power(who) {
	return BLOCKS[who].fire_power
}

function block_fire_power(who, where) {
	let combat = block_printed_fire_power(who)
	if (is_defender(who)) {
		if (is_heir(who) && is_shield_area_for(where, who, true))
			++combat
		if (is_crown_area(where) && is_senior_royal_heir_in(who, where))
			++combat
		if (is_noble(who) && is_shield_area_for(where, who, true))
			++combat
		if (is_church(who) && block_home(who) === has_cathedral(where))
			++combat
		if (is_levy(who) && block_home(who) === has_city(where))
			++combat
		if (who === B_WELSH_MERCENARY && is_wales(where))
			++combat
	}
	return combat
}

function is_mercenary(who) {
	return BLOCKS[who].type === 'mercenaries'
}

function is_heir(who) {
	return BLOCKS[who].type === 'heir'
}

function is_noble(who) {
	return BLOCKS[who].type === 'nobles'
}

function is_church(who) {
	return BLOCKS[who].type === 'church'
}

function is_levy(who) {
	return BLOCKS[who].type === 'levies'
}

function is_rose_noble(who) {
	return BLOCKS[who].type === 'nobles' && !BLOCKS[who].loyalty
}

function is_neville(who) {
	let name = block_name(who)
	return name === "Warwick" || name === "Kent" || name === "Salisbury"
}

function block_loyalty(source, target) {
	let source_name = source !== NOBODY ? block_name(source) : "Event"
	if (source_name === "Warwick") {
		let target_name = block_name(target)
		if (target_name === "Kent" || target_name === "Salisbury")
			return 1
		if (target_name === "Northumberland" || target_name === "Westmoreland")
			return 0
	}
	return BLOCKS[target].loyalty
}

function can_defect(source, target) {
	// Clarence and Exeter can't defect if they are the king or pretender
	if (target === game.king || target === game.pretender)
		return false
	return block_loyalty(source, target) > 0 && !set_has(game.defected, target)
}

function can_attempt_treason_event() {
	if (game.treason === game.attacker[game.where]) {
		for (let b = 0; b < block_count; ++b)
			if (is_defender(b) && can_defect(NOBODY, b))
				return true
	} else {
		for (let b = 0; b < block_count; ++b)
			if (is_attacker(b) && can_defect(NOBODY, b))
				return true
	}
	return false
}

function treachery_tag(who) {
	if (who === game.king) return 'King'
	if (who === game.pretender) return 'Pretender'
	if (who === B_WARWICK_L || who === B_WARWICK_Y) return 'Warwick'
	return game.active
}

function can_attempt_treachery(who) {
	let once = treachery_tag(who)
	if (set_has(game.battle_list, who) && !set_has(game.treachery, once)) {
		for (let b = 0; b < block_count; ++b) {
			if (game.active === game.attacker[game.where]) {
				if (is_defender(b) && can_defect(who, b))
					return true
			} else {
				if (is_attacker(b) && can_defect(who, b))
					return true
			}
		}
	}
	return false
}

function block_max_steps(who) {
	return BLOCKS[who].steps
}

function can_activate(who) {
	return block_owner(who) === game.active && !set_has(game.moved, who) && !set_has(game.dead, who)
}

function is_area_on_map(location) {
	return location !== NOWHERE && location !== MINOR && location !== POOL
}

function is_block_on_map(b) {
	return is_area_on_map(game.location[b])
}

function is_block_alive(b) {
	return is_area_on_map(game.location[b]) && !set_has(game.dead, b)
}

function border_id(a, b) {
	return (a < b) ? a * 100 + b : b * 100 + a
}

function border_was_last_used_by_enemy(from, to) {
	return map_get(game.last_used, border_id(from, to), 0) === PLAYER_ID[ENEMY[game.active]]
}

function border_was_last_used_by_active(from, to) {
	return map_get(game.last_used, border_id(from, to), 0) === PLAYER_ID[game.active]
}

function border_type(a, b) {
	return BORDERS[border_id(a,b)]
}

function border_limit(a, b) {
	return map_get(game.border_limit, border_id(a,b), 0)
}

function set_border_limit(a, b, n) {
	map_set(game.border_limit, border_id(a,b), n)
}

function reset_border_limits() {
	game.border_limit.length = 0
}

function count_friendly(where) {
	let p = game.active
	let count = 0
	for (let b = 0; b < block_count; ++b)
		if (game.location[b] === where && block_owner(b) === p && !set_has(game.dead, b))
			++count
	return count
}

function count_enemy(where) {
	let p = ENEMY[game.active]
	let count = 0
	for (let b = 0; b < block_count; ++b)
		if (game.location[b] === where && block_owner(b) === p && !set_has(game.dead, b))
			++count
	return count
}

function count_enemy_excluding_reserves(where) {
	let p = ENEMY[game.active]
	let count = 0
	for (let b = 0; b < block_count; ++b)
		if (game.location[b] === where && block_owner(b) === p && !set_has(game.dead, b))
			if (!set_has(game.reserves, b))
				++count
	return count
}

function is_friendly_area(where) { return is_land_area(where) && count_friendly(where) > 0 && count_enemy(where) === 0 }
function is_enemy_area(where) { return is_land_area(where) && count_friendly(where) === 0 && count_enemy(where) > 0 }
function is_vacant_area(where) { return is_land_area(where) && count_friendly(where) === 0 && count_enemy(where) === 0 }
function is_contested_area(where) { return is_land_area(where) && count_friendly(where) > 0 && count_enemy(where) > 0 }
function is_friendly_or_vacant_area(where) { return is_friendly_area(where) || is_vacant_area(where) }

function has_city(where) {
	return AREAS[where].city
}

function has_cathedral(where) {
	return AREAS[where].cathedral
}

function is_crown_area(where) {
	return AREAS[where].crown
}

function is_major_port(where) {
	return AREAS[where].major_port
}

function is_sea_area(where) {
	return where === IRISH_SEA || where === NORTH_SEA || where === ENGLISH_CHANNEL
}

function is_wales(where) {
	return where === CAERNARVON || where === PEMBROKE || where === POWYS || where === GLAMORGAN
}

function is_lancaster_exile_area(where) {
	return where === FRANCE || where === SCOTLAND
}

function is_york_exile_area(where) {
	return where === CALAIS || where === IRELAND
}

function is_exile_area(where) {
	return is_lancaster_exile_area(where) || is_york_exile_area(where)
}

function is_friendly_exile_area(where) {
	return (game.active === LANCASTER) ? is_lancaster_exile_area(where) : is_york_exile_area(where)
}

function is_enemy_exile_area(where) {
	return (game.active === YORK) ? is_lancaster_exile_area(where) : is_york_exile_area(where)
}

function is_pretender_exile_area(where) {
	return (block_owner(game.pretender) === LANCASTER) ? is_lancaster_exile_area(where) : is_york_exile_area(where)
}

function can_recruit_to(who, to) {
	if (who === B_WELSH_MERCENARY)
		return is_wales(to) && is_friendly_or_vacant_area(to)
	switch (block_type(who)) {
	case 'heir':
		// Not in rulebook, but they can be disbanded to the pool during exile limit check...
		// Use same rules as entering a minor noble.
		if (block_owner(who) === block_owner(game.king))
			return is_crown_area(to) && is_friendly_or_vacant_area(to)
		else
			return is_pretender_exile_area(to)
	case 'nobles':
		return is_shield_area_for(to, who, false) && is_friendly_or_vacant_area(to)
	case 'church':
		return block_home(who) === has_cathedral(to) && is_friendly_or_vacant_area(to)
	case 'levies':
		return block_home(who) === has_city(to) && is_friendly_or_vacant_area(to)
	case 'bombard':
		return has_city(to) && is_friendly_area(to)
	case 'rebel':
		return !is_exile_area(to) && is_vacant_area(to)
	}
	return false
}

function can_recruit(who) {
	// Move one group events:
	if (game.active === game.force_march) return false
	if (game.active === game.surprise) return false
	if (game.active === game.treason) return false

	// Must use AP for sea moves:
	if (game.active === game.piracy) return false

	if (can_activate(who) && game.location[who] === POOL)
		for (let to = first_area; to <= last_area; ++to)
			if (can_recruit_to(who, to))
				return true
	return false
}

function have_contested_areas() {
	for (let where = first_area; where <= last_area; ++where)
		if (is_area_on_map(where) && is_contested_area(where))
			return true
	return false
}

function count_pinning(where) {
	return count_enemy_excluding_reserves(where)
}

function count_pinned(where) {
	let count = 0
	for (let b = 0; b < block_count; ++b)
		if (game.location[b] === where && block_owner(b) === game.active && !set_has(game.dead, b))
			if (!set_has(game.reserves, b))
				++count
	return count
}

function is_pinned(who, from) {
	if (game.active === game.p2) {
		if (count_pinned(from) <= count_pinning(from))
			return true
	}
	return false
}

function can_block_sea_move_to(who, from, to) {
	if (is_enemy_exile_area(to))
		return false
	if (game.active === game.force_march)
		return false
	if (who === B_REBEL || who === B_SCOTS_MERCENARY || who === B_WELSH_MERCENARY)
		return false
	if (block_type(who) === 'bombard' || block_type(who) === 'levies')
		return false
	if (border_type(from, to) === 'sea')
		return true
	return false
}

function can_block_sea_move(who) {
	if (can_activate(who)) {
		let from = game.location[who]
		if (from !== NOWHERE) {
			if (is_pinned(who, from))
				return false
			for (let to of AREAS[from].exits)
				if (can_block_sea_move_to(who, from, to))
					return true
		}
	}
	return false
}

function can_block_use_border(who, from, to) {
	if (game.active === game.surprise) {
		switch (border_type(from, to)) {
		case 'major': return border_limit(from, to) < 5
		case 'river': return border_limit(from, to) < 4
		case 'minor': return border_limit(from, to) < 3
		case 'sea': return false
		}
	} else {
		switch (border_type(from, to)) {
		case 'major': return border_limit(from, to) < 4
		case 'river': return border_limit(from, to) < 3
		case 'minor': return border_limit(from, to) < 2
		case 'sea': return false
		}
	}
}

function count_borders_crossed(to) {
	let count = 0
	for (let from of AREAS[to].exits)
		if (border_was_last_used_by_active(from, to))
			++count
	return count
}

function can_block_land_move_to(who, from, to) {
	if (is_enemy_exile_area(to))
		return false
	if (game.active === game.piracy)
		return false
	if (can_block_use_border(who, from, to)) {
		// limit number of borders used to attack/reinforce
		let contested = is_contested_area(to)
		if (contested && !border_was_last_used_by_active(from, to)) {
			// p1 or p2 attacking
			if (game.attacker[to] === game.active) {
				if (count_borders_crossed(to) >= 3)
					return false
			}
			if (game.active === game.p2) {
				// p2 reinforcing battle started by p1
				if (game.attacker[to] === game.p1) {
					if (count_borders_crossed(to) >= 2)
						return false
				}
			}
		}
		if (count_pinning(from) > 0)
			if (border_was_last_used_by_enemy(from, to))
				return false
		return true
	}
	return false
}

function can_block_land_move(who) {
	if (can_activate(who)) {
		let from = game.location[who]
		if (from !== NOWHERE) {
			if (is_pinned(who, from))
				return false
			for (let to of AREAS[from].exits)
				if (can_block_land_move_to(who, from, to))
					return true
		}
	}
	return false
}

function can_block_continue(who, from, to) {
	if (is_contested_area(to))
		return false
	if (border_type(from, to) === 'minor')
		return false
	if (game.active === game.force_march) {
		if (game.distance >= 3)
			return false
	} else {
		if (game.distance >= 2)
			return false
	}
	if (to === game.last_from)
		return false
	return true
}

function can_block_retreat_to(who, to) {
	if (is_enemy_exile_area(to))
		return false
	if (is_friendly_area(to) || is_vacant_area(to)) {
		let from = game.location[who]
		if (can_block_use_border(who, from, to)) {
			if (border_was_last_used_by_enemy(from, to))
				return false
			return true
		}
	}
	return false
}

function can_block_regroup_to(who, to) {
	if (is_enemy_exile_area(to))
		return false
	if (is_friendly_area(to) || is_vacant_area(to)) {
		let from = game.location[who]
		if (can_block_use_border(who, from, to))
			return true
	}
	return false
}

function can_block_regroup(who) {
	if (block_owner(who) === game.active) {
		let from = game.location[who]
		for (let to of AREAS[from].exits)
			if (can_block_regroup_to(who, to))
				return true
	}
	return false
}

function can_block_muster_via(who, from, next, muster) {
	if (can_block_land_move_to(who, from, next) && is_friendly_or_vacant_area(next)) {
		if (next === muster)
			return true
		if (border_type(from, next) !== 'minor') {
			if (set_has(AREAS[next].exits, muster))
				if (can_block_land_move_to(who, next, muster))
					return true
		}
	}
	return false
}

function can_block_muster(who, muster) {
	let from = game.location[who]
	if (from === muster)
		return false
	if (can_activate(who) && is_block_on_map(who)) {
		if (is_pinned(who, from))
			return false
		for (let next of AREAS[from].exits)
			if (can_block_muster_via(who, from, next, muster))
				return true
	}
	return false
}

function can_muster_to(muster) {
	for (let b = 0; b < block_count; ++b)
		if (can_block_muster(b, muster))
			return true
	return false
}

function is_battle_reserve(who) {
	return set_has(game.reserves, who)
}

function is_attacker(who) {
	if (game.location[who] === game.where && block_owner(who) === game.attacker[game.where] && !set_has(game.dead, who))
		return !set_has(game.reserves, who)
	return false
}

function is_defender(who) {
	if (game.location[who] === game.where && block_owner(who) !== game.attacker[game.where] && !set_has(game.dead, who))
		return !set_has(game.reserves, who)
	return false
}

function swap_blocks(a) {
	let b = BLOCKS[a].enemy
	game.location[b] = game.location[a]
	game.steps[b] = game.steps[a]
	game.location[a] = NOWHERE
	game.steps[a] = block_max_steps(a)
	return b
}

function disband(who) {
	game.location[who] = POOL
	game.steps[who] = block_max_steps(who)
}

function check_instant_victory() {
	// Check Clarence/Y and Exeter/L specifically (they're not heirs if converted)
	if (is_dead(B_YORK) && is_dead(B_MARCH) && is_dead(B_RUTLAND) && is_dead(B_CLARENCE_Y) && is_dead(B_GLOUCESTER)) {
		log("All York heirs were eliminated!")
		game.victory = "Lancaster won by eliminating all enemy heirs!"
		game.result = LANCASTER
	}
	if (is_dead(B_HENRY_VI) && is_dead(B_PRINCE_EDWARD) && is_dead(B_EXETER_L) && is_dead(B_SOMERSET) && is_dead(B_RICHMOND)) {
		log("All Lancaster heirs were eliminated!")
		game.victory = "York won by eliminating all enemy heirs!"
		game.result = YORK
	}
}

function eliminate_block(who) {
	log(block_name(who) + " was eliminated.")
	game.flash += " " + block_name(who) + " was eliminated."
	if (who === B_EXETER_Y) {
		game.location[who] = NOWHERE
		++game.killed_heirs[LANCASTER]
		return check_instant_victory()
	}
	if (who === B_CLARENCE_L) {
		game.location[who] = NOWHERE
		++game.killed_heirs[YORK]
		return check_instant_victory()
	}
	if (is_heir(who)) {
		game.location[who] = NOWHERE
		++game.killed_heirs[block_owner(who)]
		if (who === game.pretender)
			game.pretender = find_senior_heir(block_owner(game.pretender))
		// A new King is only crowned in the supply phase.
		return check_instant_victory()
	}
	if (is_rose_noble(who) || is_neville(who)) {
		game.location[who] = NOWHERE
		return
	}
	if (is_mercenary(who)) {
		switch (who) {
		case B_WELSH_MERCENARY: game.location[who] = POOL; break
		case B_IRISH_MERCENARY: game.location[who] = IRELAND; break
		case B_BURGUNDIAN_MERCENARY: game.location[who] = CALAIS; break
		case B_CALAIS_MERCENARY: game.location[who] = CALAIS; break
		case B_SCOTS_MERCENARY: game.location[who] = SCOTLAND; break
		case B_FRENCH_MERCENARY: game.location[who] = FRANCE; break
		}
		game.steps[who] = block_max_steps(who)
		set_add(game.dead, who)
		return
	}
	game.location[who] = POOL
	game.steps[who] = block_max_steps(who)
	set_add(game.dead, who)
}

function reduce_block(who) {
	if (game.steps[who] === 1) {
		eliminate_block(who)
	} else {
		--game.steps[who]
	}
}

function count_attackers() {
	let count = 0
	for (let b = 0; b < block_count; ++b)
		if (is_attacker(b))
			++count
	return count
}

function count_defenders() {
	let count = 0
	for (let b = 0; b < block_count; ++b)
		if (is_defender(b))
			++count
	return count
}

function count_blocks_exclude_mercenaries(where) {
	let count = 0
	for (let b = 0; b < block_count; ++b)
		if (game.location[b] === where && !is_mercenary(b) && !set_has(game.dead, b) && !(game.reduced && set_has(game.reduced, b)))
			++count
	return count
}

function count_blocks(where) {
	let count = 0
	for (let b = 0; b < block_count; ++b)
		if (game.location[b] === where && !set_has(game.dead, b) && !(game.reduced && set_has(game.reduced, b)))
			++count
	return count
}

function add_blocks_exclude_mercenaries(list, where) {
	for (let b = 0; b < block_count; ++b)
		if (game.location[b] === where && !is_mercenary(b) && !set_has(game.dead, b) && !(game.reduced && set_has(game.reduced, b)))
			set_add(list, b)
}

function add_blocks(list, where) {
	for (let b = 0; b < block_count; ++b)
		if (game.location[b] === where && !set_has(game.dead, b) && !(game.reduced && set_has(game.reduced, b)))
			set_add(list, b)
}

function check_supply_penalty() {
	game.supply = []
	for (let where = first_area; where <= last_area; ++where) {
		if (is_friendly_area(where)) {
			if (where === CALAIS || where === FRANCE) {
				if (count_blocks_exclude_mercenaries(where) > 4)
					add_blocks_exclude_mercenaries(game.supply, where)
			} else if (where === IRELAND || where === SCOTLAND) {
				if (count_blocks_exclude_mercenaries(where) > 2)
					add_blocks_exclude_mercenaries(game.supply, where)
			} else if (has_city(where)) {
				if (count_blocks(where) > 5)
					add_blocks(game.supply, where)
			} else {
				if (count_blocks(where) > 4)
					add_blocks(game.supply, where)
			}
		}
	}
	return game.supply.length > 0
}

function check_exile_limits() {
	game.exiles = []
	for (let where = first_area; where <= last_area; ++where) {
		if (is_friendly_area(where)) {
			if (where === CALAIS || where === FRANCE) {
				if (count_blocks_exclude_mercenaries(where) > 4)
					add_blocks_exclude_mercenaries(game.exiles, where)
			} else if (where === IRELAND || where === SCOTLAND) {
				if (count_blocks_exclude_mercenaries(where) > 2)
					add_blocks_exclude_mercenaries(game.exiles, where)
			}
		}
	}
	if (game.exiles.length > 0)
		return true
	delete game.exiles
	return false
}

// SETUP

function find_block(owner, name) {
	if (name in block_index)
		return block_index[name]
	name = name + "/" + owner[0]
	if (name in block_index)
		return block_index[name]
	throw new Error("Block not found: " + name)
}

function deploy(who, where) {
	if (where === "Enemy")
		return
	if (!(where in area_index))
		throw new Error("Area not found: " + where)
	game.location[who] = area_index[where]
	game.steps[who] = BLOCKS[who].steps
}

function deploy_lancaster(name, where) {
	deploy(find_block(LANCASTER, name), where)
}

function deploy_york(name, where) {
	deploy(find_block(YORK, name), where)
}

function reset_blocks() {
	for (let b = 0; b < block_count; ++b) {
		game.location[b] = NOWHERE
		game.steps[b] = block_max_steps(b)
	}
}

function setup_game() {
	reset_blocks()

	game.campaign = 1
	game.end_campaign = 3
	game.pretender = B_YORK
	game.king = B_HENRY_VI

	deploy_lancaster("Henry VI", "Middlesex")
	deploy_lancaster("Somerset", "Dorset")
	deploy_lancaster("Exeter", "Cornwall")
	deploy_lancaster("Devon", "Cornwall")
	deploy_lancaster("Pembroke", "Pembroke")
	deploy_lancaster("Wiltshire", "Wilts")
	deploy_lancaster("Oxford", "Essex")
	deploy_lancaster("Beaumont", "Lincoln")
	deploy_lancaster("Clifford", "North Yorks")
	deploy_lancaster("French Mercenary", "France")
	deploy_lancaster("Scots Mercenary", "Scotland")
	deploy_lancaster("Buckingham", "Pool")
	deploy_lancaster("Northumberland", "Pool")
	deploy_lancaster("Shrewsbury", "Pool")
	deploy_lancaster("Westmoreland", "Pool")
	deploy_lancaster("Rivers", "Pool")
	deploy_lancaster("Stanley", "Pool")
	deploy_lancaster("Bristol (levy)", "Pool")
	deploy_lancaster("Coventry (levy)", "Pool")
	deploy_lancaster("Newcastle (levy)", "Pool")
	deploy_lancaster("York (levy)", "Pool")
	deploy_lancaster("York (church)", "Pool")
	deploy_lancaster("Bombard", "Pool")
	deploy_lancaster("Welsh Mercenary", "Pool")
	deploy_lancaster("Prince Edward", "Minor")
	deploy_lancaster("Richmond", "Minor")
	deploy_lancaster("Canterbury (church)", "Enemy")
	deploy_lancaster("Clarence", "Enemy")
	deploy_lancaster("Warwick", "Enemy")
	deploy_lancaster("Salisbury", "Enemy")
	deploy_lancaster("Kent", "Enemy")

	deploy_york("York", "Ireland")
	deploy_york("Rutland", "Ireland")
	deploy_york("Irish Mercenary", "Ireland")
	deploy_york("March", "Calais")
	deploy_york("Warwick", "Calais")
	deploy_york("Salisbury", "Calais")
	deploy_york("Kent", "Calais")
	deploy_york("Calais Mercenary", "Calais")
	deploy_york("Burgundian Mercenary", "Calais")
	deploy_york("Norfolk", "Pool")
	deploy_york("Suffolk", "Pool")
	deploy_york("Arundel", "Pool")
	deploy_york("Essex", "Pool")
	deploy_york("Worcester", "Pool")
	deploy_york("Hastings", "Pool")
	deploy_york("Herbert", "Pool")
	deploy_york("Canterbury (church)", "Pool")
	deploy_york("London (levy)", "Pool")
	deploy_york("Norwich (levy)", "Pool")
	deploy_york("Salisbury (levy)", "Pool")
	deploy_york("Bombard", "Pool")
	deploy_york("Rebel", "Pool")
	deploy_york("Clarence", "Minor")
	deploy_york("Gloucester", "Minor")
	deploy_york("Exeter", "Enemy")
	deploy_york("Buckingham", "Enemy")
	deploy_york("Northumberland", "Enemy")
	deploy_york("Westmoreland", "Enemy")
	deploy_york("Shrewsbury", "Enemy")
	deploy_york("Rivers", "Enemy")
	deploy_york("Stanley", "Enemy")
	deploy_york("York (church)", "Enemy")
}

function setup_kingmaker() {
	reset_blocks()

	game.campaign = 2
	game.end_campaign = 2
	game.pretender = B_HENRY_VI
	game.king = B_MARCH

	deploy_york("March", "Middlesex")
	deploy_york("Gloucester", "South Yorks")
	deploy_york("Buckingham", "Warwick")
	deploy_york("Norfolk", "East Anglia")
	deploy_york("Suffolk", "East Anglia")
	deploy_york("Arundel", "Sussex")
	deploy_york("Essex", "Essex")
	deploy_york("Hastings", "Leicester")
	deploy_york("Rivers", "Leicester")
	deploy_york("Stanley", "Lancaster")
	deploy_york("Irish Mercenary", "Ireland")
	deploy_york("Calais Mercenary", "Calais")
	deploy_york("Burgundian Mercenary", "Calais")
	deploy_york("Northumberland", "Pool")
	deploy_york("Westmoreland", "Pool")
	deploy_york("Canterbury (church)", "Pool")
	deploy_york("Bombard", "Pool")
	deploy_york("London (levy)", "Pool")
	deploy_york("Norwich (levy)", "Pool")
	deploy_york("Salisbury (levy)", "Pool")
	deploy_york("Warwick", "Enemy")
	deploy_york("Clarence", "Enemy")
	deploy_york("Shrewsbury", "Enemy")
	deploy_york("York (church)", "Enemy")
	deploy_york("Exeter", "Enemy")

	deploy_lancaster("Henry VI", "Middlesex")
	deploy_lancaster("Prince Edward", "France")
	deploy_lancaster("Exeter", "France")
	deploy_lancaster("Warwick", "France")
	deploy_lancaster("Clarence", "France")
	deploy_lancaster("Oxford", "France")
	deploy_lancaster("French Mercenary", "France")
	deploy_lancaster("Scots Mercenary", "Scotland")
	deploy_lancaster("Pembroke", "Pool")
	deploy_lancaster("Shrewsbury", "Pool")
	deploy_lancaster("York (church)", "Pool")
	deploy_lancaster("Welsh Mercenary", "Pool")
	deploy_lancaster("Bombard", "Pool")
	deploy_lancaster("Bristol (levy)", "Pool")
	deploy_lancaster("Coventry (levy)", "Pool")
	deploy_lancaster("Newcastle (levy)", "Pool")
	deploy_lancaster("York (levy)", "Pool")
	deploy_lancaster("Rebel", "Pool")
	deploy_lancaster("Richmond", "Minor")
	deploy_lancaster("Buckingham", "Enemy")
	deploy_lancaster("Northumberland", "Enemy")
	deploy_lancaster("Rivers", "Enemy")
	deploy_lancaster("Westmoreland", "Enemy")
	deploy_lancaster("Stanley", "Enemy")
	deploy_lancaster("Canterbury (church)", "Enemy")

	// Prisoner!
	set_add(game.dead, B_HENRY_VI)
}

function setup_richard_iii() {
	reset_blocks()

	game.campaign = 3
	game.end_campaign = 3
	game.pretender = B_RICHMOND
	game.king = B_GLOUCESTER

	deploy_york("Gloucester", "Middlesex")
	deploy_york("Norfolk", "East Anglia")
	deploy_york("Suffolk", "East Anglia")
	deploy_york("Arundel", "Sussex")
	deploy_york("Essex", "Essex")
	deploy_york("Northumberland", "Northumbria")
	deploy_york("Stanley", "Lancaster")
	deploy_york("Irish Mercenary", "Ireland")
	deploy_york("Calais Mercenary", "Calais")
	deploy_york("Burgundian Mercenary", "Calais")
	deploy_york("Westmoreland", "Pool")
	deploy_york("Canterbury (church)", "Pool")
	deploy_york("York (church)", "Pool")
	deploy_york("Bombard", "Pool")
	deploy_york("London (levy)", "Pool")
	deploy_york("Norwich (levy)", "Pool")
	deploy_york("Salisbury (levy)", "Pool")
	deploy_york("Buckingham", "Enemy")
	deploy_york("Shrewsbury", "Enemy")
	deploy_york("Rivers", "Enemy")

	deploy_lancaster("Richmond", "France")
	deploy_lancaster("Oxford", "France")
	deploy_lancaster("Pembroke", "France")
	deploy_lancaster("French Mercenary", "France")
	deploy_lancaster("Scots Mercenary", "Scotland")
	deploy_lancaster("Buckingham", "Glamorgan")
	deploy_lancaster("Rivers", "Leicester")
	deploy_lancaster("Shrewsbury", "Pool")
	deploy_lancaster("Welsh Mercenary", "Pool")
	deploy_lancaster("Bombard", "Pool")
	deploy_lancaster("Bristol (levy)", "Pool")
	deploy_lancaster("Coventry (levy)", "Pool")
	deploy_lancaster("Newcastle (levy)", "Pool")
	deploy_lancaster("York (levy)", "Pool")
	deploy_lancaster("Rebel", "Pool")
	deploy_lancaster("Northumberland", "Enemy")
	deploy_lancaster("Westmoreland", "Enemy")
	deploy_lancaster("Stanley", "Enemy")
	deploy_lancaster("Canterbury (church)", "Enemy")
	deploy_lancaster("York (church)", "Enemy")
}

// Kingmaker scenario special rule
function free_henry_vi() {
	if (set_has(game.dead, B_HENRY_VI)) {
		if ((game.active === LANCASTER && is_friendly_area(MIDDLESEX)) ||
			(game.active === YORK && is_enemy_area(MIDDLESEX))) {
			log("Henry VI rescued!")
			set_delete(game.dead, B_HENRY_VI)
		}
	}
}

// GAME TURN

function start_campaign() {
	logbr()
	log(".h1 Campaign " + game.campaign)
	logbr()

	// TODO: Use board game mulligan rules instead of automatically redealing?
	do {
		let deck = shuffle_deck()
		game.l_hand = deal_cards(deck, 7)
		game.y_hand = deal_cards(deck, 7)
	} while (count_ap(game.l_hand) <= 13 || count_ap(game.y_hand) <= 13)

	start_game_turn()
}

function start_game_turn() {
	game.turn = 8 - game.l_hand.length

	logbr()
	log(".h1 Turn " + game.turn + " of campaign " + game.campaign + ".")
	logbr()

	// Reset movement and attack tracking state
	reset_border_limits()
	game.last_used = []
	game.attacker = {}
	set_clear(game.reserves)
	set_clear(game.moved)

	goto_card_phase()
}

function end_game_turn() {
	delete game.force_march
	delete game.piracy
	delete game.is_pirate
	delete game.surprise
	delete game.treason

	if (game.l_hand.length > 0)
		start_game_turn()
	else
		goto_political_turn()
}

// CARD PHASE

function goto_card_phase() {
	game.l_card = 0
	game.y_card = 0
	game.show_cards = false
	game.state = 'play_card'
	game.active = BOTH
}

function resume_play_card() {
	if (game.l_card > 0 && game.y_card > 0)
		reveal_cards()
	else if (game.l_card > 0)
		game.active = YORK
	else if (game.y_card > 0)
		game.active = LANCASTER
	else
		game.active = BOTH
}

states.play_card = {
	prompt: function (view, current) {
		if (current === OBSERVER)
			return view.prompt = "Waiting for players to play a card."
		if (current === LANCASTER) {
			if (game.l_card) {
				view.prompt = "Waiting for York to play a card."
			} else {
				view.prompt = "Play a card."
				for (let c of game.l_hand)
					gen_action(view, 'play', c)
			}
		}
		if (current === YORK) {
			if (game.y_card) {
				view.prompt = "Waiting for Lancaster to play a card."
			} else {
				view.prompt = "Play a card."
				for (let c of game.y_hand)
					gen_action(view, 'play', c)
			}
		}
	},
	play: function (card, current) {
		if (current === LANCASTER) {
			remove_from_array(game.l_hand, card)
			game.l_card = card
		}
		if (current === YORK) {
			remove_from_array(game.y_hand, card)
			game.y_card = card
		}
		resume_play_card()
	},
	undo: function (_, current) {
		if (current === LANCASTER) {
			game.l_hand.push(game.l_card)
			game.l_card = 0
		}
		if (current === YORK) {
			game.y_hand.push(game.y_card)
			game.y_card = 0
		}
		resume_play_card()
	}
}

function reveal_cards() {
	logbr()
	log("Lancaster played " + CARDS[game.l_card].name + ".")
	log("York played " + CARDS[game.y_card].name + ".")
	game.show_cards = true

	let pretender = block_owner(game.pretender)

	let lc = CARDS[game.l_card]
	let yc = CARDS[game.y_card]

	let lp = (lc.event ? 10 : 0) + lc.actions * 2 + (pretender === LANCASTER ? 1 : 0)
	let yp = (yc.event ? 10 : 0) + yc.actions * 2 + (pretender === YORK ? 1 : 0)

	if (lp > yp) {
		game.p1 = LANCASTER
		game.p2 = YORK
	} else {
		game.p1 = YORK
		game.p2 = LANCASTER
	}

	game.active = game.p1
	start_player_turn()
}

function start_player_turn() {
	logbr()
	log(".h2 " + game.active)

	reset_border_limits()
	let lc = CARDS[game.l_card]
	let yc = CARDS[game.y_card]
	if (game.active === LANCASTER && lc.event)
		goto_event_card(lc.event)
	else if (game.active === YORK && yc.event)
		goto_event_card(yc.event)
	else if (game.active === LANCASTER)
		goto_action_phase(lc.actions)
	else if (game.active === YORK)
		goto_action_phase(yc.actions)
}

function end_player_turn() {
	game.moves = 0
	game.activated = null
	game.move_port = null
	game.main_border = null

	// Remove "Surprise" road limit bonus for retreats and regroups.
	delete game.surprise

	if (game.active === game.p2) {
		goto_battle_phase()
	} else {
		game.active = game.p2
		start_player_turn()
	}
}

// EVENTS

function goto_event_card(event) {
	switch (event) {
	case 'force_march':
		game.force_march = game.active
		goto_action_phase(1)
		break
	case 'muster':
		goto_muster_event()
		break
	case 'piracy':
		game.piracy = game.active
		game.is_pirate = []
		goto_action_phase(2)
		break
	case 'plague':
		game.state = 'plague_event'
		break
	case 'surprise':
		game.surprise = game.active
		goto_action_phase(1)
		break
	case 'treason':
		game.treason = game.active
		goto_action_phase(1)
		break
	}
}

states.plague_event = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Plague: Waiting for " + game.active + " to choose a city."
		view.prompt = "Plague: Choose an enemy city area."
		gen_action(view, 'pass')
		for (let where = first_area; where <= last_area; ++where)
			if (is_enemy_area(where) && has_city(where))
				gen_action(view, 'area', where)
	},
	area: function (where) {
		log("Plague ravaged " + has_city(where) + "!")
		game.where = where
		game.plague = []
		for (let b = 0; b < block_count; ++b)
			if (game.location[b] === where && !set_has(game.dead, b))
				set_add(game.plague, b)
		game.active = ENEMY[game.active]
		game.state = 'apply_plague'
	},
	pass: function () {
		end_player_turn()
	}
}

states.apply_plague = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Plague: Waiting for " + game.active + " to reduce blocks in " + has_city(game.where) + "."
		view.prompt = "Plague: Reduce blocks in " + has_city(game.where) + "."
		for (let b of game.plague)
			gen_action(view, 'block', b)
	},
	block: function (b) {
		reduce_block(b)
		set_delete(game.plague, b)
		if (game.plague.length === 0) {
			delete game.plague
			game.active = ENEMY[game.active]
			game.where = NOWHERE
			end_player_turn()
		}
	},
}

function goto_muster_event() {
	game.state = 'muster_event'
	game.turn_log = []
	clear_undo()
}

states.muster_event = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Muster: Waiting for " + game.active + " to muster."
		view.prompt = "Muster: Choose one friendly or vacant muster area."
		gen_action_undo(view)
		gen_action(view, 'end_action_phase')
		for (let where = first_area; where <= last_area; ++where) {
			if (is_friendly_or_vacant_area(where))
				if (can_muster_to(where))
					gen_action(view, 'area', where)
		}
	},
	area: function (where) {
		push_undo()
		game.where = where
		game.state = 'muster_who'
	},
	end_action_phase: function () {
		clear_undo()
		print_turn_log(game.active + " mustered:")
		end_player_turn()
	},
	undo: pop_undo,
}

states.muster_who = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Muster: Waiting for " + game.active + " to muster."
		view.prompt = "Muster: Move blocks to the designated muster area."
		gen_action_undo(view)
		gen_action(view, 'end_action_phase')
		for (let b = 0; b < block_count; ++b)
			if (can_block_muster(b, game.where))
				gen_action(view, 'block', b)
	},
	block: function (who) {
		push_undo()
		game.who = who
		game.state = 'muster_move_1'
	},
	end_action_phase: function () {
		game.where = NOWHERE
		clear_undo()
		print_turn_log(game.active + " mustered:")
		end_player_turn()
	},
	undo: pop_undo,
}

states.muster_move_1 = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Muster: Waiting for " + game.active + " to muster."
		view.prompt = "Muster: Move " + block_name(game.who) + " to the designated muster area."
		gen_action_undo(view)
		gen_action(view, 'block', game.who)
		let from = game.location[game.who]
		for (let to of AREAS[from].exits) {
			if (can_block_muster_via(game.who, from, to, game.where))
				gen_action(view, 'area', to)
		}
	},
	area: function (to) {
		let from = game.location[game.who]
		log_move_start(from)
		log_move_continue(to)
		move_block(game.who, from, to)
		if (to === game.where) {
			log_move_end()
			set_add(game.moved, game.who)
			game.who = NOBODY
			game.state = 'muster_who'
		} else {
			game.state = 'muster_move_2'
		}
	},
	block: pop_undo,
	undo: pop_undo,
}

states.muster_move_2 = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Muster: Waiting for " + game.active + " to muster."
		view.prompt = "Muster: Move " + block_name(game.who) + " to the designated muster area."
		gen_action_undo(view)
		gen_action(view, 'area', game.where)
	},
	area: function (to) {
		log_move_continue(to)
		log_move_end()
		move_block(game.who, game.location[game.who], to)
		set_add(game.moved, game.who)
		game.who = NOBODY
		game.state = 'muster_who'
	},
	undo: pop_undo,
}

// ACTION PHASE

function use_border(from, to) {
	set_border_limit(from, to, border_limit(from, to) + 1)
}

function move_block(who, from, to) {
	game.location[who] = to
	use_border(from, to)
	game.distance ++
	if (is_contested_area(to)) {
		map_set(game.last_used, border_id(from, to), PLAYER_ID[game.active])
		if (!game.attacker[to]) {
			game.attacker[to] = game.active
			map_set(game.main_border, to, from)
		} else {
			if (game.attacker[to] !== game.active || map_get(game.main_border, to, 0) !== from) {
				set_add(game.reserves, who)
				return RESERVE_MARK
			}
		}
		return ATTACK_MARK
	}
	return ""
}

function goto_action_phase(moves) {
	game.state = 'action_phase'
	game.moves = moves
	game.activated = []
	game.move_port = []
	game.main_border = []
	game.turn_log = []
	game.recruit_log = []
	clear_undo()
}

states.action_phase = {
	prompt: function (view, current) {
		if (is_inactive_player(current)) {
			if (game.active === game.piracy)
				return view.prompt = "Piracy: Waiting for " + game.active + "."
			if (game.active === game.force_march)
				return view.prompt = "Force March: Waiting for " + game.active + "."
			if (game.active === game.surprise)
				return view.prompt = "Surprise: Waiting for " + game.active + "."
			if (game.active === game.treason)
				return view.prompt = "Treason: Waiting for " + game.active + "."
			else
				return view.prompt = "Action Phase: Waiting for " + game.active + "."
		}

		if (game.active === game.piracy) {
			view.prompt = "Piracy: Choose an army to sea move. Attacking is allowed. " + game.moves + "AP left."
		} else if (game.active === game.force_march) {
			view.prompt = "Force March: Move one group. Blocks can move up to 3 areas and may attack."
		} else if (game.active === game.surprise) {
			view.prompt = "Surprise: Move one group. Border limit is +1 to cross all borders."
		} else if (game.active === game.treason) {
			view.prompt = "Treason: Move one group."
		} else {
			view.prompt = "Action Phase: Choose an army to move or recruit. " + game.moves + "AP left."
		}

		gen_action_undo(view)
		gen_action(view, 'end_action_phase')
		for (let b = 0; b < block_count; ++b) {
			let from = game.location[b]
			if (can_recruit(b)) {
				if (game.moves > 0)
					gen_action(view, 'block', b)
			}
			if (can_block_land_move(b)) {
				if (game.moves === 0) {
					if (set_has(game.activated, from))
						gen_action(view, 'block', b)
				} else {
					gen_action(view, 'block', b)
				}
			}
			if (can_block_sea_move(b)) {
				if (game.moves === 0) {
					if (map_has(game.move_port, game.location[b]))
						gen_action(view, 'block', b)
				} else {
					gen_action(view, 'block', b)
				}
			}
		}
	},
	block: function (who) {
		push_undo()
		game.who = who
		game.origin = game.location[who]
		if (game.origin === POOL) {
			game.state = 'recruit_where'
		} else {
			game.distance = 0
			game.last_from = NOWHERE
			game.state = 'move_to'
		}
	},
	end_action_phase: function () {
		if (game.moves > 0 && game.turn_log.length === 0 && game.recruit_log.length === 0)
			logp("did nothing.")

		if (game.turn_log.length > 0) {
			print_turn_log(game.active + " moved:")
		}
		game.turn_log = game.recruit_log
		if (game.turn_log.length > 0) {
			print_turn_log(game.active + " recruited:")
		}
		game.turn_log = null
		game.recruit_log = null

		clear_undo()
		game.moves = 0
		end_player_turn()
	},
	undo: pop_undo,
}

states.recruit_where = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Action Phase: Waiting for " + game.active + "."
		view.prompt = "Recruit " + block_name(game.who) + " where?"
		gen_action_undo(view)
		gen_action(view, 'block', game.who)
		for (let to = first_area; to <= last_area; ++to)
			if (can_recruit_to(game.who, to))
				gen_action(view, 'area', to)
	},
	area: function (to) {
		game.recruit_log.push(["#" + to])
		--game.moves
		game.location[game.who] = to
		set_add(game.moved, game.who)
		end_action()
	},
	block: pop_undo,
	undo: pop_undo,
}

states.move_to = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Action Phase: Waiting for " + game.active + "."
		view.prompt = "Move " + block_name(game.who) + "."
		gen_action_undo(view)
		gen_action(view, 'block', game.who)
		let from = game.location[game.who]
		if (game.distance > 0)
			gen_action(view, 'area', from)
		for (let to of AREAS[from].exits) {
			if (to !== game.last_from && can_block_land_move_to(game.who, from, to))
				gen_action(view, 'area', to)
			else if (game.distance === 0 && can_block_sea_move_to(game.who, from, to)) {
				let has_destination_port = false
				if (game.moves === 0) {
					for (let port of AREAS[to].exits)
						if (map_get(game.move_port, game.origin) === port)
							has_destination_port = true
				} else {
					if (game.active === game.piracy)
						has_destination_port = true
					else
						for (let port of AREAS[to].exits)
							if (port !== game.origin && is_friendly_or_vacant_area(port))
								has_destination_port = true
				}
				if (has_destination_port)
					gen_action(view, 'area', to)
			}
		}
	},
	block: function () {
		if (game.distance === 0)
			pop_undo()
		else
			end_move()
	},
	area: function (to) {
		let from = game.location[game.who]
		if (to === from) {
			end_move()
			return
		}
		if (game.distance === 0)
			log_move_start(from)
		game.last_from = from
		if (is_sea_area(to)) {
			// XXX use_border(from, to) // if displaying sea moves
			log_move_continue(to)
			game.location[game.who] = to
			game.state = 'sea_move_to'
		} else {
			let mark = move_block(game.who, from, to)
			log_move_continue(to, mark)
			if (!can_block_continue(game.who, from, to))
				end_move()
		}
	},
	undo: pop_undo,
}

states.sea_move_to = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Action Phase: Waiting for " + game.active + "."
		if (game.active === game.piracy) {
			view.prompt = "Piracy: Sea Move " + block_name(game.who) + " to a coastal area."
		} else {
			view.prompt = "Sea Move " + block_name(game.who) + " to a friendly or vacant coastal area."
		}
		gen_action_undo(view)
		for (let to of AREAS[game.location[game.who]].exits) {
			if (to === game.last_from)
				continue
			if (is_enemy_exile_area(to))
				continue
			if (is_friendly_or_vacant_area(to)) {
				if (game.moves === 0) {
					if (map_get(game.move_port, game.origin) === to)
						gen_action(view, 'area', to)
				} else {
					gen_action(view, 'area', to)
				}
			} else if (game.active === game.piracy && game.moves > 0) {
				// Can attack with piracy, but no port-to-port bonus.
				gen_action(view, 'area', to)
			}
		}
	},
	area: function (to) {
		// XXX use_border(game.location[game.who], to) // if displaying sea moves

		game.location[game.who] = to
		set_add(game.moved, game.who)

		if (game.active === game.piracy && is_contested_area(to)) {
			// Can attack with piracy, but no port-to-port bonus.
			log_move_continue(to, ATTACK_MARK)
			set_add(game.is_pirate, game.who)
			if (!game.attacker[to])
				game.attacker[to] = game.active
			logp("sea moved.")
			--game.moves
		} else {
			// Can sea move two blocks between same major ports for 1 AP.
			log_move_continue(to)
			if (map_get(game.move_port, game.origin) === to) {
				map_delete(game.move_port, game.origin)
			} else {
				logp("sea moved.")
				--game.moves
				if (is_major_port(game.origin) && is_major_port(to))
					map_set(game.move_port, game.origin, to)
			}
		}

		log_move_end()
		end_action()
	},
	undo: pop_undo,
}

function end_move() {
	if (game.distance > 0) {
		log_move_end()
		if (!set_has(game.activated, game.origin)) {
			logp("activated #" + game.origin + ".")
			set_add(game.activated, game.origin)
			game.moves --
		}
		set_add(game.moved, game.who)
	}
	game.last_from = NOWHERE
	end_action()
}

function end_action() {
	free_henry_vi()
	game.who = NOBODY
	game.distance = 0
	game.origin = NOWHERE
	game.state = 'action_phase'
}

// BATTLE PHASE

function goto_battle_phase() {
	reset_border_limits()
	if (have_contested_areas()) {
		game.active = game.p1
		game.state = 'battle_phase'
	} else {
		goto_supply_phase()
	}
}

states.battle_phase = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to choose a battle."
		view.prompt = "Choose the next battle to fight!"
		for (let where = first_area; where <= last_area; ++where)
			if (is_area_on_map(where) && is_contested_area(where))
				gen_action(view, 'area', where)
	},
	area: function (where) {
		start_battle(where)
	},
}

function start_battle(where) {
	game.flash = ""
	logbr()
	log(".h3 Battle in #" + where)
	game.where = where
	game.battle_round = 0
	game.defected = []
	game.treachery = []

	if (game.treason && can_attempt_treason_event()) {
		game.active = game.treason
		game.state = 'treason_event'
	} else {
		game.state = 'battle_round'
		start_battle_round()
	}
}

function resume_battle() {
	if (game.result)
		return goto_game_over()
	game.who = NOBODY
	game.state = 'battle_round'
	pump_battle_round()
}

function end_battle() {
	if (game.turn_log && game.turn_log.length > 0)
		print_turn_log("Retreated from #" + game.where + ":")
	free_henry_vi()
	game.flash = ""
	game.battle_round = 0
	reset_border_limits()
	set_clear(game.moved)
	game.defected = []
	game.treachery = []
	goto_regroup()
}

states.treason_event = {
	show_battle: true,
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Treason: Waiting for " + game.active + " to choose a target."
		view.prompt = "Treason: Choose a target or pass."
		gen_action(view, 'pass')
		for (let b = 0; b < block_count; ++b) {
			if (game.active === game.attacker[game.where]) {
				if (is_defender(b) && can_defect(NOBODY, b)) {
					gen_action(view, 'battle_treachery', b)
					gen_action(view, 'block', b)
				}
			} else {
				if (is_attacker(b) && can_defect(NOBODY, b)) {
					gen_action(view, 'battle_treachery', b)
					gen_action(view, 'block', b)
				}
			}
		}
	},
	battle_treachery: function (target) {
		delete game.treason
		attempt_treachery(NOBODY, target)
		game.state = 'battle_round'
		start_battle_round()
	},
	block: function (target) {
		delete game.treason
		attempt_treachery(NOBODY, target)
		game.state = 'battle_round'
		start_battle_round()
	},
	pass: function () {
		game.state = 'battle_round'
		start_battle_round()
	}
}

function bring_on_reserves(owner, moved) {
	for (let b = 0; b < block_count; ++b) {
		if (block_owner(b) === owner && game.location[b] === game.where && !set_has(game.dead, b)) {
			set_delete(game.reserves, b)
			if (moved)
				set_add(game.moved, b)
			else
				set_delete(game.moved, b)
		}
	}
}

function start_battle_round() {
	if (++game.battle_round <= 4) {
		if (game.turn_log && game.turn_log.length > 0)
			print_turn_log("Retreated from #" + game.where + ":")
		game.turn_log = []

		log(".h4 Battle Round " + game.battle_round)

		reset_border_limits()
		set_clear(game.moved)

		if (game.battle_round > 1) {
			bring_on_reserves(LANCASTER, false)
			bring_on_reserves(YORK, false)
		}

		pump_battle_round()
	} else {
		end_battle()
	}
}

function pump_battle_round() {
	if (is_friendly_area(game.where) || is_enemy_area(game.where)) {
		end_battle()
		return
	}

	if (count_attackers() === 0 || count_defenders() === 0) {
		// Deploy reserves immediately if all blocks on one side are eliminated.
		if (count_attackers() === 0) {
			log("Attacking main force was eliminated.")
			bring_on_reserves(game.attacker[game.where], true)
		} else if (count_defenders() === 0) {
			log("Defending main force was eliminated.")
			bring_on_reserves(ENEMY[game.attacker[game.where]], true)
			if (game.battle_round === 1) {
				log("Battlefield control changed.")
				game.attacker[game.where] = ENEMY[game.attacker[game.where]]
			}
		}
	}

	function filter_battle_blocks(ci, is_candidate) {
		let output = null
		for (let b = 0; b < block_count; ++b) {
			if (is_candidate(b) && !set_has(game.moved, b) && !set_has(game.dead, b)) {
				if (block_initiative(b) === ci) {
					if (!output)
						output = []
					set_add(output, b)
				}
			}
		}
		return output
	}

	function battle_step(active, initiative, candidate) {
		game.battle_list = filter_battle_blocks(initiative, candidate)
		if (game.battle_list) {
			game.active = active
			return true
		}
		return false
	}

	let attacker = game.attacker[game.where]
	let defender = ENEMY[attacker]

	if (battle_step(defender, 'A', is_defender)) return
	if (battle_step(attacker, 'A', is_attacker)) return
	if (battle_step(defender, 'B', is_defender)) return
	if (battle_step(attacker, 'B', is_attacker)) return
	if (battle_step(defender, 'C', is_defender)) return
	if (battle_step(attacker, 'C', is_attacker)) return
	if (battle_step(defender, 'D', is_defender)) return
	if (battle_step(attacker, 'D', is_attacker)) return

	start_battle_round()
}

function pass_with_block(b) {
	game.flash = block_name(b) + " passed."
	log_battle(game.flash)
	set_add(game.moved, b)
	resume_battle()
}

function can_retreat_with_block(who) {
	if (game.location[who] === game.where) {
		if (game.battle_round > 1) {
			if (game.active === game.piracy && set_has(game.is_pirate, who)) {
				return true
			} else {
				for (let to of AREAS[game.where].exits)
					if (can_block_retreat_to(who, to))
						return true
			}
		}
	}
	return false
}

function must_retreat_with_block(who) {
	if (game.location[who] === game.where)
		if (game.battle_round === 4)
			return (block_owner(who) === game.attacker[game.where])
	return false
}

function retreat_with_block(who) {
	if (can_retreat_with_block(who)) {
		game.who = who
		game.state = 'retreat_in_battle'
	} else {
		eliminate_block(who)
		resume_battle()
	}
}

function roll_attack(active, b, verb) {
	game.hits = 0
	let fire = block_fire_power(b, game.where)
	let printed_fire = block_printed_fire_power(b)
	let rolls = []
	let steps = game.steps[b]
	let name = block_name(b) + " " + BLOCKS[b].combat
	if (fire > printed_fire)
		name += "+" + (fire - printed_fire)
	for (let i = 0; i < steps; ++i) {
		let die = roll_d6()
		if (die <= fire) {
			rolls.push(DIE_HIT[die])
			++game.hits
		} else {
			rolls.push(DIE_MISS[die])
		}
	}

	game.flash = name + " " + verb + " " + rolls.join(" ") + " "
	if (game.hits === 0)
		game.flash += "and missed."
	else if (game.hits === 1)
		game.flash += "and scored 1 hit."
	else
		game.flash += "and scored " + game.hits + " hits."

	log(active[0] + ": " + name + " " + verb + " " + rolls.join("") + ".")
}

function fire_with_block(b) {
	set_add(game.moved, b)
	roll_attack(game.active, b, "fired")
	if (game.hits > 0) {
		game.active = ENEMY[game.active]
		goto_battle_hits()
	} else {
		resume_battle()
	}
}

function attempt_treachery(source, target) {
	if (source !== NOBODY) {
		let once = treachery_tag(source)
		set_add(game.treachery, once)
		set_add(game.moved, source)
	}
	let n = block_loyalty(source, target)
	let rolls = []
	let result = true
	for (let i = 0; i < n; ++i) {
		let die = roll_d6()
		if ((die & 1) === 1) {
			rolls.push(DIE_MISS[die])
			result = false
		} else {
			rolls.push(DIE_HIT[die])
		}
	}
	if (source !== NOBODY)
		game.flash = block_name(source) + " treachery " + rolls.join(" ")
	else
		game.flash = "Treason event " + rolls.join(" ")
	if (result) {
		game.flash += " converted " + block_name(target) + "!"
		target = swap_blocks(target)
		set_add(game.defected, target)
		set_add(game.reserves, target)
	} else {
		game.flash += " failed to convert " + block_name(target) + "."
	}
	log_battle(game.flash)
}

function charge_with_block(heir, target) {
	let n
	set_add(game.moved, heir)
	roll_attack(game.active, heir, "charged " + block_name(target))
	n = Math.min(game.hits, game.steps[target])
	if (n === game.steps[target]) {
		eliminate_block(target)
	} else {
		while (n-- > 0)
			reduce_block(target)
		let charge_flash = game.flash
		roll_attack(ENEMY[game.active], target, "counter-attacked")
		n = Math.min(game.hits, game.steps[heir])
		while (n-- > 0)
			reduce_block(heir)
		game.flash = charge_flash + " " + game.flash
	}
	resume_battle()
}

function can_block_fire(who) {
	if (is_attacker(who))
		return game.battle_round < 4
	if (is_defender(who))
		return true
	return false
}

function find_minor_heir(owner) {
	let candidate = NOBODY
	for (let b = 0; b < block_count; ++b) {
		if (block_owner(b) === owner && block_type(b) === 'heir' && game.location[b] === MINOR)
			if (candidate === NOBODY || BLOCKS[b].heir < BLOCKS[candidate].heir)
				candidate = b
	}
	return candidate
}

function find_senior_heir(owner) {
	let candidate = NOBODY
	for (let b = 0; b < block_count; ++b)
		if (block_owner(b) === owner && block_type(b) === 'heir' && !is_dead(b))
			if (candidate === NOBODY || BLOCKS[b].heir < BLOCKS[candidate].heir)
				candidate = b
	return candidate
}

function find_next_king(owner) {
	let candidate = NOBODY
	for (let b = 0; b < block_count; ++b)
		if (block_owner(b) === owner && block_type(b) === 'heir' && game.location[b] !== NOWHERE)
			if (candidate === NOBODY || BLOCKS[b].heir < BLOCKS[candidate].heir)
				candidate = b
	return candidate
}

function find_senior_heir_in_area(owner, where) {
	let candidate = NOBODY
	for (let b = 0; b < block_count; ++b) {
		if (block_owner(b) === owner && block_type(b) === 'heir' && game.location[b] === where) {
			if (is_battle_reserve(b))
				continue
			if (candidate === NOBODY || BLOCKS[b].heir < BLOCKS[candidate].heir)
				candidate = b
		}
	}
	return candidate
}

function is_senior_royal_heir_in(who, where) {
	return find_senior_heir_in_area(block_owner(game.king), where) === who
}

function can_heir_charge() {
	let heir = find_senior_heir_in_area(game.active, game.where)
	if (heir !== NOBODY && !set_has(game.moved, heir)) {
		if (is_attacker(heir))
			return game.battle_round < 4 ? heir : NOBODY
		if (is_defender(heir))
			return heir
	}
	return NOBODY
}

states.battle_round = {
	show_battle: true,
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to choose a combat action."
		view.prompt = "Battle: Choose a combat action with an army."

		let can_fire = false
		let can_retreat = false
		let must_retreat = false
		let can_pass = false
		if (game.active === game.attacker[game.where]) {
			if (game.battle_round < 4) can_fire = true
			if (game.battle_round > 1) can_retreat = true
			if (game.battle_round < 4) can_pass = true
			if (game.battle_round === 4) must_retreat = true
		} else {
			can_fire = true
			if (game.battle_round > 1) can_retreat = true
			can_pass = true
		}

		for (let b of game.battle_list) {
			if (can_fire) gen_action(view, 'battle_fire', b)
			if (must_retreat || (can_retreat && can_retreat_with_block(b)))
				gen_action(view, 'battle_retreat', b)
			if (can_pass) gen_action(view, 'battle_pass', b)
			gen_action(view, 'block', b)
		}

		if (!must_retreat) {
			let heir = can_heir_charge()
			if (heir !== NOBODY && set_has(game.battle_list, heir))
				gen_action(view, 'battle_charge', heir)
			if (can_attempt_treachery(game.king))
				gen_action(view, 'battle_treachery', game.king)
			if (can_attempt_treachery(game.pretender))
				gen_action(view, 'battle_treachery', game.pretender)
			if (can_attempt_treachery(B_WARWICK_L))
				gen_action(view, 'battle_treachery', B_WARWICK_L)
			if (can_attempt_treachery(B_WARWICK_Y))
				gen_action(view, 'battle_treachery', B_WARWICK_Y)
		}
	},
	battle_fire: function (who) {
		fire_with_block(who)
	},
	battle_retreat: function (who) {
		retreat_with_block(who)
	},
	battle_pass: function (who) {
		pass_with_block(who)
	},
	battle_charge: function (who) {
		game.who = who
		game.state = 'battle_charge'
	},
	battle_treachery: function (who) {
		game.who = who
		game.state = 'battle_treachery'
	},
	block: function (who) {
		if (can_block_fire(who))
			fire_with_block(who)
		else if (can_retreat_with_block(who))
			retreat_with_block(who)
		else if (must_retreat_with_block(who)) {
			eliminate_block(who)
			resume_battle()
		} else
			pass_with_block(who)
	},
}

states.battle_charge = {
	show_battle: true,
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Heir Charge: Waiting for " + game.active + " to choose a target."
		view.prompt = "Heir Charge: Choose a target."
		gen_action(view, 'undo')
		for (let b = 0; b < block_count; ++b) {
			if (game.active === game.attacker[game.where]) {
				if (is_defender(b)) {
					gen_action(view, 'battle_charge', b)
					gen_action(view, 'block', b)
				}
			} else {
				if (is_attacker(b)) {
					gen_action(view, 'battle_charge', b)
					gen_action(view, 'block', b)
				}
			}
		}
	},
	battle_charge: function (target) {
		charge_with_block(game.who, target)
	},
	block: function (target) {
		charge_with_block(game.who, target)
	},
	undo: function () {
		resume_battle()
	}
}

states.battle_treachery = {
	show_battle: true,
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Treachery: Waiting for " + game.active + " to choose a target."
		view.prompt = "Treachery: Choose a target."
		gen_action(view, 'undo')
		for (let b = 0; b < block_count; ++b) {
			if (game.active === game.attacker[game.where]) {
				if (is_defender(b) && can_defect(game.who, b)) {
					gen_action(view, 'battle_treachery', b)
					gen_action(view, 'block', b)
				}
			} else {
				if (is_attacker(b) && can_defect(game.who, b)) {
					gen_action(view, 'battle_treachery', b)
					gen_action(view, 'block', b)
				}
			}
		}
	},
	battle_treachery: function (target) {
		attempt_treachery(game.who, target)
		resume_battle()
	},
	block: function (target) {
		attempt_treachery(game.who, target)
		resume_battle()
	},
	undo: function () {
		resume_battle()
	}
}

function goto_battle_hits() {
	game.battle_list = list_victims(game.active)
	if (game.battle_list.length === 0)
		resume_battle()
	else
		game.state = 'battle_hits'
}

function apply_hit(who) {
	let n = Math.min(game.hits, game.steps[who])
	if (n === 1)
		game.flash = block_name(who) + " took " + n + " hit."
	else
		game.flash = block_name(who) + " took " + n + " hits."
	log_battle(game.flash)
	while (n-- > 0) {
		reduce_block(who)
		game.hits--
	}
	game.battle_list = list_victims(game.active)
	if (game.battle_list.length > 0) {
		if (game.hits === 1)
			game.flash += " 1 hit left."
		else if (game.hits > 1)
			game.flash += " " + game.hits + " hits left."
	}
	if (game.hits === 0)
		resume_battle()
	else
		goto_battle_hits()
}

function list_victims(p) {
	let is_candidate = (p === game.attacker[game.where]) ? is_attacker : is_defender
	let max = 0
	for (let b = 0; b < block_count; ++b)
		if (is_candidate(b) && game.steps[b] > max)
			max = game.steps[b]
	let list = []
	for (let b = 0; b < block_count; ++b)
		if (is_candidate(b) && game.steps[b] === max)
			set_add(list, b)
	return list
}

states.battle_hits = {
	show_battle: true,
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to assign hits."
		view.prompt = "Assign " + game.hits + (game.hits !== 1 ? " hits" : " hit") + " to your armies."
		for (let b of game.battle_list) {
			gen_action(view, 'battle_hit', b)
			gen_action(view, 'block', b)
		}
	},
	battle_hit: function (who) {
		apply_hit(who)
	},
	block: function (who) {
		apply_hit(who)
	},
}

states.retreat_in_battle = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to retreat."
		gen_action(view, 'undo')
		gen_action(view, 'block', game.who)
		if (game.active === game.piracy && set_has(game.is_pirate, game.who)) {
			view.prompt = "Retreat: Move the army to a friendly or vacant areas in the same sea zone."
			for (let to of AREAS[game.where].exits)
				if (is_sea_area(to))
					gen_action(view, 'area', to)
		} else {
			view.prompt = "Retreat: Move the army to a friendly or vacant area."
			for (let to of AREAS[game.where].exits)
				if (can_block_retreat_to(game.who, to))
					gen_action(view, 'area', to)
		}
	},
	area: function (to) {
		if (is_sea_area(to)) {
			game.location[game.who] = to
			game.state = 'sea_retreat_to'
		} else {
			game.flash = block_name(game.who) + " retreated."
			log_battle(game.flash)
			game.turn_log.push([game.active, "#" + to])
			use_border(game.where, to)
			game.location[game.who] = to
			resume_battle()
		}
	},
	eliminate: function () {
		game.flash = ""
		eliminate_block(game.who)
		resume_battle()
	},
	block: function () {
		resume_battle()
	},
	undo: function () {
		resume_battle()
	}
}

states.sea_retreat_to = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to retreat."
		view.prompt = "Retreat: Move the army to a friendly or vacant area in the same sea zone."
		// TODO: only eliminate if no retreat is possible
		gen_action(view, 'eliminate')
		let from = game.location[game.who]
		for (let to of AREAS[from].exits)
			if (is_friendly_or_vacant_area(to))
				gen_action(view, 'area', to)
	},
	area: function (to) {
		let sea = game.location[game.who]
		game.turn_log.push([game.active, "#" + sea, "#" + to])
		game.flash = block_name(game.who) + " retreated."
		log_battle(game.flash)
		game.location[game.who] = to
		resume_battle()
	},
	eliminate: function () {
		game.flash = ""
		eliminate_block(game.who)
		resume_battle()
	},
	undo: function () {
		game.location[game.who] = game.where
		resume_battle()
	}
}

function goto_regroup() {
	game.active = game.attacker[game.where]
	if (is_enemy_area(game.where))
		game.active = ENEMY[game.active]
	log(game.active + " won the battle in #" + game.where + "!")
	game.state = 'regroup'
	game.turn_log = []
	clear_undo()
}

function is_attacker_with_piracy() {
	return game.active === game.piracy && game.active === game.attacker[game.where]
}

states.regroup = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to regroup."
		view.prompt = "Regroup: Choose an army to move."
		gen_action_undo(view)
		gen_action(view, 'end_regroup')
		for (let b = 0; b < block_count; ++b) {
			if (game.location[b] === game.where && !set_has(game.dead, b)) {
				if (is_attacker_with_piracy()) {
					if (set_has(game.is_pirate, b))
						gen_action(view, 'block', b)
				} else {
					if (can_block_regroup(b))
						gen_action(view, 'block', b)
				}
			}
		}
	},
	block: function (who) {
		push_undo()
		game.who = who
		game.state = 'regroup_to'
	},
	end_regroup: function () {
		game.where = NOWHERE
		clear_undo()
		print_turn_log(game.active + " regrouped:")
		goto_battle_phase()
	},
	undo: pop_undo,
}

states.regroup_to = {
	prompt: function (view, current) {
		if (is_attacker_with_piracy() && set_has(game.is_pirate, game.who)) {
			if (is_inactive_player(current))
				return view.prompt = "Waiting for " + game.active + " to regroup."
			view.prompt = "Regroup: Move the army to a friendly or vacant area in the same sea zone."
			gen_action_undo(view)
			gen_action(view, 'block', game.who)
			for (let to of AREAS[game.where].exits)
				if (is_sea_area(to))
					gen_action(view, 'area', to)
		} else {
			if (is_inactive_player(current))
				return view.prompt = "Waiting for " + game.active + " to regroup."
			view.prompt = "Regroup: Move the army to a friendly or vacant area."
			gen_action_undo(view)
			gen_action(view, 'block', game.who)
			for (let to of AREAS[game.where].exits)
				if (can_block_regroup_to(game.who, to))
					gen_action(view, 'area', to)
		}
	},
	area: function (to) {
		if (is_sea_area(to)) {
			log_move_start(game.where)
			log_move_continue(to)
			game.location[game.who] = to
			game.state = 'sea_regroup_to'
		} else {
			game.turn_log.push(["#"+game.where, "#"+to])
			move_block(game.who, game.where, to)
			game.who = NOBODY
			game.state = 'regroup'
		}
	},
	block: pop_undo,
	undo: pop_undo,
}

states.sea_regroup_to = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to regroup."
		view.prompt = "Regroup: Move the army to a friendly or vacant area in the same sea zone."
		gen_action_undo(view)
		let from = game.location[game.who]
		for (let to of AREAS[from].exits)
			if (is_friendly_or_vacant_area(to))
				gen_action(view, 'area', to)
	},
	area: function (to) {
		log_move_continue(to)
		log_move_end()
		game.location[game.who] = to
		game.who = NOBODY
		game.state = 'regroup'
	},
	undo: pop_undo,
}

// SUPPLY PHASE

function goto_supply_phase() {
	set_clear(game.moved)

	if (game.location[game.king] === NOWHERE) {
		game.king = find_next_king(block_owner(game.king))
		log("The King is dead; long live the king!")
		if (game.location[game.king] === MINOR)
			log("The new King is a minor.")
		else
			log("The new King is in #" + game.location[game.king] + ".")
	}

	goto_execute_clarence()
}

function goto_execute_clarence() {
	if (is_block_alive(B_CLARENCE_L)) {
		game.active = LANCASTER
		game.state = 'execute_clarence'
		game.who = B_CLARENCE_L
	} else {
		goto_execute_exeter()
	}
}

states.execute_clarence = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to execute Clarence."
		view.prompt = "Supply Phase: Execute enemy heir Clarence?"
		gen_action(view, 'execute_clarence')
		gen_action(view, 'pass')
	},
	execute_clarence: function () {
		logp("executed Clarence.")
		eliminate_block(B_CLARENCE_L)
		game.who = NOBODY
		if (game.result)
			return goto_game_over()
		goto_execute_exeter()
	},
	pass: function () {
		game.who = NOBODY
		goto_execute_exeter()
	}
}

function goto_execute_exeter() {
	if (is_block_alive(B_EXETER_Y)) {
		game.active = YORK
		game.state = 'execute_exeter'
		game.who = B_EXETER_Y
	} else {
		goto_enter_pretender_heir()
	}
}

states.execute_exeter = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to execute Exeter."
		view.prompt = "Supply Phase: Execute enemy heir Exeter?"
		gen_action(view, 'execute_exeter')
		gen_action(view, 'pass')
	},
	execute_exeter: function () {
		logp("executed Exeter.")
		eliminate_block(B_EXETER_Y)
		game.who = NOBODY
		if (game.result)
			return goto_game_over()
		goto_enter_pretender_heir()
	},
	pass: function () {
		game.who = NOBODY
		goto_enter_pretender_heir()
	}
}

// PRETENDER SUPPLY PHASE

function goto_enter_pretender_heir() {
	game.active = block_owner(game.pretender)
	let n = game.killed_heirs[game.active]
	if (n > 0 && (game.who = find_minor_heir(game.active)) !== NOBODY)
		game.state = 'enter_pretender_heir'
	else
		goto_supply_limits_pretender()
}

states.enter_pretender_heir = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to enter pretender heirs."
		view.prompt = "Death of an Heir: Enter " + block_name(game.who) + " in an exile area."
		for (let where = first_area; where <= last_area; ++where)
			if (is_pretender_exile_area(where))
				gen_action(view, 'area', where)
	},
	area: function (to) {
		logbr()
		log(block_name(game.who) + " came of age in #" + to + ".")
		--game.killed_heirs[game.active]
		game.location[game.who] = to
		game.who = NOBODY
		goto_enter_pretender_heir()
	},
}

function goto_supply_limits_pretender() {
	game.reduced = []
	game.active = block_owner(game.pretender)
	if (check_supply_penalty()) {
		game.state = 'supply_limits_pretender'
		game.turn_log = []
		clear_undo()
	} else {
		delete game.supply
		delete game.reduced
		goto_enter_royal_heir()
	}
}

states.supply_limits_pretender = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to check supply limits."
		view.prompt = "Supply Phase: Reduce blocks in over-stacked areas."
		gen_action_undo(view)
		if (game.supply.length === 0)
			gen_action(view, 'end_supply_phase')
		for (let b of game.supply)
			gen_action(view, 'block', b)
	},
	block: function (who) {
		push_undo()
		game.turn_log.push(["#" + game.location[who]])
		set_add(game.reduced, who)
		reduce_block(who)
		check_supply_penalty()
	},
	end_supply_phase: function () {
		delete game.supply
		delete game.reduced
		clear_undo()
		print_turn_log(game.active + " reduced:")
		if (game.result)
			return goto_game_over()
		goto_enter_royal_heir()
	},
	undo: pop_undo,
}

// KING SUPPLY PHASE

function goto_enter_royal_heir() {
	game.active = block_owner(game.king)
	let n = game.killed_heirs[game.active]
	if (n > 0 && (game.who = find_minor_heir(game.active)) !== NOBODY)
		game.state = 'enter_royal_heir'
	else
		goto_supply_limits_king()
}

states.enter_royal_heir = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to enter royal heirs."
		view.prompt = "Death of an Heir: Enter " + block_name(game.who) + " in a Crown area."
		let can_enter = false
		for (let where = first_area; where <= last_area; ++where) {
			if (is_crown_area(where) && is_friendly_or_vacant_area(where)) {
				gen_action(view, 'area', where)
				can_enter = true
			}
		}
		if (!can_enter)
			gen_action(view, 'pass')
	},
	area: function (to) {
		logbr()
		log(block_name(game.who) + " came of age in #" + to + ".")
		--game.killed_heirs[game.active]
		game.location[game.who] = to
		game.who = NOBODY
		goto_enter_royal_heir()
	},
	pass: function () {
		game.who = NOBODY
		goto_supply_limits_king()
	}
}

function goto_supply_limits_king() {
	game.reduced = []
	game.active = block_owner(game.king)
	if (check_supply_penalty()) {
		game.state = 'supply_limits_king'
		game.turn_log = []
		clear_undo()
	} else {
		delete game.supply
		delete game.reduced
		end_game_turn()
	}
}

states.supply_limits_king = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to check supply limits."
		view.prompt = "Supply Phase: Reduce blocks in over-stacked areas."
		gen_action_undo(view)
		if (game.supply.length === 0)
			gen_action(view, 'end_supply_phase')
		for (let b of game.supply)
			gen_action(view, 'block', b)
	},
	block: function (who) {
		push_undo()
		game.turn_log.push(["#" + game.location[who]])
		set_add(game.reduced, who)
		reduce_block(who)
		check_supply_penalty()
	},
	end_supply_phase: function () {
		delete game.supply
		delete game.reduced
		clear_undo()
		print_turn_log(game.active + " reduced:")
		if (game.result)
			return goto_game_over()
		end_game_turn()
	},
	undo: pop_undo,
}

// POLITICAL TURN

function goto_political_turn() {
	logbr()
	log(".h1 Political Turn")
	logbr()

	game.turn_log = []

	// Levies disband
	for (let b = 0; b < block_count; ++b) {
		if (!is_land_area(game.location[b]))
			continue
		switch (block_type(b)) {
		case 'bombard':
		case 'levies':
		case 'rebel':
			game.turn_log.push(["#" + game.location[b]])
			disband(b)
			break
		case 'mercenaries':
			switch (b) {
			case B_WELSH_MERCENARY:
				game.turn_log.push(["#" + game.location[b]])
				disband(b)
				break
			case B_IRISH_MERCENARY:
				if (game.location[b] !== IRELAND) {
					game.turn_log.push(["#" + game.location[b], "#" + IRELAND])
					game.location[b] = IRELAND
				}
				break
			case B_BURGUNDIAN_MERCENARY:
			case B_CALAIS_MERCENARY:
				if (game.location[b] !== CALAIS) {
					game.turn_log.push(["#" + game.location[b], "#" + CALAIS])
					game.location[b] = CALAIS
				}
				break
			case B_SCOTS_MERCENARY:
				if (game.location[b] !== SCOTLAND) {
					game.turn_log.push(["#" + game.location[b], "#" + SCOTLAND])
					game.location[b] = SCOTLAND
				}
				break
			case B_FRENCH_MERCENARY:
				if (game.location[b] !== FRANCE) {
					game.turn_log.push(["#" + game.location[b], "#" + FRANCE])
					game.location[b] = FRANCE
				}
				break
			}
			break
		}
	}

	print_turn_log("Levies disbanded:")

	// Usurpation
	let l_count = count_lancaster_nobles_and_heirs()
	let y_count = count_york_nobles_and_heirs()
	logbr()
	log("Lancaster controlled " + l_count + " nobles.")
	log("York controlled " + y_count + " nobles.")
	if (l_count > y_count && block_owner(game.king) === YORK) {
		game.king = find_senior_heir(LANCASTER)
		game.pretender = find_senior_heir(YORK)
		log(block_name(game.king) + " usurped the throne!")
	} else if (y_count > l_count && block_owner(game.king) === LANCASTER) {
		game.king = find_senior_heir(YORK)
		game.pretender = find_senior_heir(LANCASTER)
		log(block_name(game.king) + " usurped the throne!")
	} else {
		log(block_name(game.king) + " remained king.")
	}

	// Game ends after last Usurpation check
	if (game.campaign === game.end_campaign)
		return goto_game_over()

	logbr()
	goto_pretender_goes_home()
}

// PRETENDER GOES HOME

function goto_pretender_goes_home() {
	game.active = block_owner(game.pretender)
	game.state = 'pretender_goes_home'
	game.turn_log = []
	let choices = false
	for (let b = 0; b < block_count; ++b)
		if (block_owner(b) === game.active && is_block_on_map(b) && !set_has(game.dead, b))
			if (pretender_go_home_if_possible(b))
				choices = true
	if (!choices) {
		print_turn_log_no_count("Pretender went home:")
		goto_exile_limits_pretender()
	} else {
		clear_undo()
	}
}

states.pretender_goes_home = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for the Pretender to go to exile."
		gen_action_undo(view)
		let done = true
		for (let b = 0; b < block_count; ++b) {
			if (block_owner(b) === game.active && is_block_on_map(b) && !set_has(game.dead, b) && !set_has(game.moved, b)) {
				if (!is_in_exile(b)) {
					if (is_heir(b)) {
						done = false
						gen_action(view, 'block', b)
					} else if (!is_at_home(b)) {
						done = false
						let n = count_available_homes(b)
						if (n > 1)
							gen_action(view, 'block', b)
					}
				}
			}
		}
		if (done) {
			view.prompt = "Pretender Goes Home: You may move nobles to another home."
			for (let b = 0; b < block_count; ++b) {
				if (block_owner(b) === game.active && is_block_on_map(b) && !set_has(game.dead, b) && !set_has(game.moved, b)) {
					if (!is_in_exile(b)) {
						if (is_at_home(b)) {
							let n = count_available_homes(b)
							if (n > 1)
								gen_action(view, 'block', b)
						}
					}
				}
			}
			gen_action(view, 'end_political_turn')
		} else {
			view.prompt = "Pretender Goes Home: Move the pretender and his heirs to exile, and nobles to home."
		}
	},
	block: function (who) {
		push_undo()
		game.who = who
		game.state = 'pretender_goes_home_to'
	},
	end_political_turn: function () {
		clear_undo()
		print_turn_log_no_count("Pretender went home:")
		goto_exile_limits_pretender()
	},
	undo: pop_undo,
}

states.pretender_goes_home_to = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for the Pretender to go to exile."
		if (is_heir(game.who))
			view.prompt = "Pretender Goes Home: Move " + block_name(game.who) + " to exile."
		else
			view.prompt = "Pretender Goes Home: Move " + block_name(game.who) + " to home."
		gen_action(view, 'block', game.who)
		for (let where = first_area; where <= last_area; ++where) {
			if (where !== game.location[game.who]) {
				if (is_heir(game.who)) {
					if (is_friendly_exile_area(where))
						gen_action(view, 'area', where)
				} else if (is_available_home_for(where, game.who)) {
					gen_action(view, 'area', where)
				}
			}
		}
	},
	area: function (to) {
		if (is_exile_area(to))
			game.turn_log.push([block_name(game.who), "#" + to]) // TODO: "Exile"?
		else
			game.turn_log.push([block_name(game.who), "#" + to]) // TODO: "Home"?
		set_add(game.moved, game.who)
		game.location[game.who] = to
		game.who = NOBODY
		game.state = 'pretender_goes_home'
	},
	block: pop_undo,
	undo: pop_undo,
}

function goto_exile_limits_pretender() {
	set_clear(game.moved)
	game.active = block_owner(game.pretender)
	if (check_exile_limits()) {
		game.state = 'exile_limits_pretender'
		clear_undo()
	} else {
		goto_king_goes_home()
	}
}

states.exile_limits_pretender = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to check exile limits."
		view.prompt = "Campaign Reset: Disband one block in each over-stacked exile area."
		gen_action_undo(view)
		if (game.exiles.length === 0)
			gen_action(view, 'end_exile_limits')
		for (let b of game.exiles)
			gen_action(view, 'block', b)
	},
	block: function (who) {
		push_undo()
		let where = game.location[who]
		logp("disbanded in #" + where + ".")
		game.exiles = game.exiles.filter(b => game.location[b] !== where)
		disband(who)
	},
	end_exile_limits: function () {
		goto_king_goes_home()
	},
	undo: pop_undo,
}

// KING GOES HOME

function goto_king_goes_home() {
	game.active = block_owner(game.king)
	game.state = 'king_goes_home'
	game.turn_log = []
	let choices = false
	for (let b = 0; b < block_count; ++b)
		if (block_owner(b) === game.active && is_block_on_map(b) && !set_has(game.dead, b))
			if (king_go_home_if_possible(b))
				choices = true
	if (!choices) {
		print_turn_log_no_count("King went home:")
		goto_exile_limits_king()
	} else {
		clear_undo()
	}
}

states.king_goes_home = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for the King to go home."
		gen_action_undo(view)
		let done = true
		for (let b = 0; b < block_count; ++b) {
			if (block_owner(b) === game.active && is_block_on_map(b) && !set_has(game.dead, b) && !set_has(game.moved, b)) {
				if (!is_in_exile(b)) {
					if (!is_at_home(b)) {
						done = false
						let n = count_available_homes(b)
						if (n > 1)
							gen_action(view, 'block', b)
					}
				}
			}
		}
		if (done) {
			view.prompt = "King Goes Home: You may move nobles and heirs to another home."
			for (let b = 0; b < block_count; ++b) {
				if (block_owner(b) === game.active && is_block_on_map(b) && !set_has(game.dead, b) && !set_has(game.moved, b)) {
					if (!is_in_exile(b)) {
						if (is_at_home(b)) {
							let n = count_available_homes(b)
							if (n > 1)
								gen_action(view, 'block', b)
						}
					}
				}
			}
			gen_action(view, 'end_political_turn')
		} else {
			view.prompt = "King Goes Home: Move the King, the royal heirs, and nobles to home."
		}
	},
	block: function (who) {
		push_undo()
		game.who = who
		game.state = 'king_goes_home_to'
	},
	end_political_turn: function () {
		clear_undo()
		print_turn_log_no_count("King went home:")
		goto_exile_limits_king()
	},
	undo: pop_undo,
}

states.king_goes_home_to = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for the King to go home."
		view.prompt = "King Goes Home: Move " + block_name(game.who) + " to home."
		gen_action(view, 'block', game.who)
		for (let where = first_area; where <= last_area; ++where)
			if (where !== game.location[game.who])
				if (is_available_home_for(where, game.who))
					gen_action(view, 'area', where)
	},
	area: function (to) {
		game.turn_log.push([block_name(game.who), "#" + to]) // TODO: "Home"?
		set_add(game.moved, game.who)
		game.location[game.who] = to
		game.who = NOBODY
		game.state = 'king_goes_home'
	},
	block: pop_undo,
	undo: pop_undo,
}

function goto_exile_limits_king() {
	set_clear(game.moved)
	game.active = block_owner(game.king)
	if (check_exile_limits()) {
		game.state = 'exile_limits_king'
		clear_undo()
	} else {
		end_political_turn()
	}
}

states.exile_limits_king = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to check exile limits."
		view.prompt = "Campaign Reset: Disband one block in each over-stacked exile area."
		gen_action_undo(view)
		if (game.exiles.length === 0)
			gen_action(view, 'end_exile_limits')
		for (let b of game.exiles)
			gen_action(view, 'block', b)
	},
	block: function (who) {
		push_undo()
		let where = game.location[who]
		logp("disbanded in #" + where + ".")
		game.exiles = game.exiles.filter(b => game.location[b] !== where)
		disband(who)
	},
	end_exile_limits: function () {
		end_political_turn()
	},
	undo: pop_undo,
}

function end_political_turn() {
	// Campaign reset
	set_clear(game.dead)
	for (let b = 0; b < block_count; ++b)
		game.steps[b] = block_max_steps(b)

	++game.campaign
	start_campaign()
}

// GAME OVER

function goto_game_over() {
	game.active = "None"
	game.state = 'game_over'
	if (!game.result) {
		game.result = block_owner(game.king)
		game.victory = game.result + " won!"
	}
	logbr()
	log(game.victory)
}

states.game_over = {
	prompt: function (view) {
		view.prompt = game.victory
	}
}

function make_battle_view() {
	let battle = {
		round: game.battle_round,
		LF: [], LR: [],
		YF: [], YR: [],
		flash: game.flash
	}

	battle.title = game.attacker[game.where] + " attacks " + AREAS[game.where].name
	battle.title += " \u2014 round " + game.battle_round + " of 4"

	function fill_cell(cell, owner, fn) {
		for (let b = 0; b < block_count; ++b)
			if (game.location[b] === game.where & block_owner(b) === owner && !set_has(game.dead, b) && fn(b))
				cell.push(b)
	}

	fill_cell(battle.LR, LANCASTER, b => is_battle_reserve(b))
	fill_cell(battle.LF, LANCASTER, b => !is_battle_reserve(b))
	fill_cell(battle.YR, YORK, b => is_battle_reserve(b))
	fill_cell(battle.YF, YORK, b => !is_battle_reserve(b))

	return battle
}

exports.setup = function (seed, scenario, options) {
	game = {
		seed: seed,
		log: [],
		undo: [],

		state: null,
		active: null,
		turn: 0,
		moves: 0,
		who: NOBODY,
		where: NOWHERE,

		show_cards: false,
		killed_heirs: { Lancaster: 0, York: 0 },
		king: NOBODY,
		pretender: NOBODY,

		location: [],
		steps: [],
		moved: [],
		dead: [],
		reserves: [],

		attacker: {},
		border_limit: [],
		last_used: [],
		main_border: [],
	}

	// Old RNG for ancient replays
	if (options.rng)
		game.rng = options.rng

	if (scenario === "Wars of the Roses")
		setup_game()
	else if (scenario === "Kingmaker")
		setup_kingmaker()
	else if (scenario === "Richard III")
		setup_richard_iii()
	else
		throw new Error("Unknown scenario:", scenario)

	logbr()
	log(".h1 " + scenario)
	logbr()

	start_campaign()
	return game
}

exports.action = function (state, current, action, arg) {
	game = state
	let S = states[game.state]
	if (action in S)
		S[action](arg, current)
	else
		throw new Error("Invalid action: " + action)
	return game
}

function observer_hand() {
	let hand = []
	hand.length = Math.max(game.l_hand.length, game.y_hand.length)
	hand.fill(0)
	return hand
}

exports.view = function(state, current) {
	game = state

	let view = {
		log: game.log,
		campaign: game.campaign + " of " + game.end_campaign,
		active: game.active,
		king: game.king,
		pretender: game.pretender,
		l_card: (game.show_cards || current === LANCASTER) ? game.l_card : 0,
		y_card: (game.show_cards || current === YORK) ? game.y_card : 0,
		hand: (current === LANCASTER) ? game.l_hand : (current === YORK) ? game.y_hand : observer_hand(),
		who: (game.active === current) ? game.who : NOBODY,
		where: game.where,
		location: game.location,
		steps: game.steps,
		moved: game.moved,
		dead: game.dead,
		last_used: game.last_used,
		border_limit: game.border_limit,
		battle: null,
		prompt: null,
	}

	if (game.main_border && game.main_border.length > 0) {
		view.main_border = []
		for (let i = 0; i < game.main_border.length; i += 2)
			set_add(view.main_border, border_id(game.main_border[i+0], game.main_border[i+1]))
	}

	states[game.state].prompt(view, current)

	if (states[game.state].show_battle)
		view.battle = make_battle_view()

	return view
}

// === COMMON LIBRARY ===

// remove item at index (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
	return array
}

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

// insert item at index (faster than splice)
function array_insert(array, index, item) {
	for (let i = array.length; i > index; --i)
		array[i] = array[i - 1]
	array[index] = item
	return array
}

function array_insert_pair(array, index, key, value) {
	for (let i = array.length; i > index; i -= 2) {
		array[i] = array[i-2]
		array[i+1] = array[i-1]
	}
	array[index] = key
	array[index+1] = value
}

function set_clear(set) {
	set.length = 0
}

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 set
	}
	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
			return array_remove(set, m)
	}
	return set
}

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

function map_get(map, key, missing) {
	let a = 0
	let b = (map.length >> 1) - 1
	while (a <= b) {
		let m = (a + b) >> 1
		let x = map[m<<1]
		if (key < x)
			b = m - 1
		else if (key > x)
			a = m + 1
		else
			return map[(m<<1)+1]
	}
	return missing
}

function map_set(map, key, value) {
	let a = 0
	let b = (map.length >> 1) - 1
	while (a <= b) {
		let m = (a + b) >> 1
		let x = map[m<<1]
		if (key < x)
			b = m - 1
		else if (key > x)
			a = m + 1
		else {
			map[(m<<1)+1] = value
			return
		}
	}
	array_insert_pair(map, a<<1, key, value)
}

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

// 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
	}
}

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
}