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

exports.scenarios = [
	"Braveheart",
	"The Bruce",
	"Campaign",
]

exports.roles = [
	"England",
	"Scotland",
]

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

const block_count = BLOCKS.length
const area_count = AREAS.length
const first_map_area = 3

const ENEMY = { Scotland: "England", England: "Scotland" }

const PID = { "": 0, Scotland: 1, England: 2 }
const UNPID = [ "", "Scotland", "England" ]

const OBSERVER = "Observer"
const BOTH = "Both"
const ENGLAND = "England"
const SCOTLAND = "Scotland"

const NOWHERE = 0
const E_BAG = area_index["E. Bag"]
const S_BAG = area_index["S. Bag"]

const AREA_ENGLAND = area_index["England"]
const AREA_ROSS = area_index["Ross"]
const AREA_GARMORAN = area_index["Garmoran"]
const AREA_MORAY = area_index["Moray"]
const AREA_STRATHSPEY = area_index["Strathspey"]
const AREA_BUCHAN = area_index["Buchan"]
const AREA_LOCHABER = area_index["Lochaber"]
const AREA_BADENOCH = area_index["Badenoch"]
const AREA_MAR = area_index["Mar"]
const AREA_ANGUS = area_index["Angus"]
const AREA_ARGYLL = area_index["Argyll"]
const AREA_ATHOLL = area_index["Atholl"]
const AREA_LENNOX = area_index["Lennox"]
const AREA_MENTIETH = area_index["Mentieth"]
const AREA_FIFE = area_index["Fife"]
const AREA_CARRICK = area_index["Carrick"]
const AREA_LANARK = area_index["Lanark"]
const AREA_LOTHIAN = area_index["Lothian"]
const AREA_SELKIRK = area_index["Selkirk"]
const AREA_DUNBAR = area_index["Dunbar"]
const AREA_GALLOWAY = area_index["Galloway"]
const AREA_ANNAN = area_index["Annan"]
const AREA_TEVIOT = area_index["Teviot"]

const NOBODY = -1
const B_EDWARD = block_index["Edward"]
const B_KING = block_index["King"]
const B_MORAY = block_index["Moray"]
const B_WALLACE = block_index["Wallace"]
const B_NORSE = block_index["Norse"]
const B_FRENCH_KNIGHTS = block_index["French Knights"]
const B_BRUCE_E = block_index["Bruce/E"]
const B_BRUCE_S = block_index["Bruce/S"]
const B_COMYN_E = block_index["Comyn/E"]
const B_COMYN_S = block_index["Comyn/S"]

const ENGLISH_NOBLES = {
	"Angus": block_index["Angus/E"],
	"Argyll": block_index["Argyll/E"],
	"Atholl": block_index["Atholl/E"],
	"Bruce": block_index["Bruce/E"],
	"Buchan": block_index["Buchan/E"],
	"Comyn": block_index["Comyn/E"],
	"Dunbar": block_index["Dunbar/E"],
	"Galloway": block_index["Galloway/E"],
	"Lennox": block_index["Lennox/E"],
	"Mar": block_index["Mar/E"],
	"Mentieth": block_index["Mentieth/E"],
	"Ross": block_index["Ross/E"],
	"Steward": block_index["Steward/E"],
}

const SCOTTISH_NOBLES = {
	"Angus": block_index["Angus/S"],
	"Argyll": block_index["Argyll/S"],
	"Atholl": block_index["Atholl/S"],
	"Bruce": block_index["Bruce/S"],
	"Buchan": block_index["Buchan/S"],
	"Comyn": block_index["Comyn/S"],
	"Dunbar": block_index["Dunbar/S"],
	"Galloway": block_index["Galloway/S"],
	"Lennox": block_index["Lennox/S"],
	"Mar": block_index["Mar/S"],
	"Mentieth": block_index["Mentieth/S"],
	"Ross": block_index["Ross/S"],
	"Steward": block_index["Steward/S"],
}

// 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 log(s) {
	game.log.push(s)
}

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

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

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_no_active(text) {
	game.turn_log.sort()
	log(text)
	let last = game.turn_log[0]
	let n = 0
	for (let entry of game.turn_log) {
		if (entry.toString() !== last.toString()) {
			logi(n + " " + last.join(" \u2192 "))
			n = 0
		}
		++n
		last = entry
	}
	if (n > 0)
		logi(n + " " + last.join(" \u2192 "))
	else
		logi("nothing.")
	delete game.turn_log
}

function print_turn_log(verb) {
	print_turn_log_no_active(game.active + " " + verb + ":")
}

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
			view.actions[action].push(argument)
	} else {
		view.actions[action] = 1
	}
}

function gen_action_battle(view, action, b) {
	gen_action(view, action, b)
}

function gen_action_block(view, b) {
	gen_action(view, 'block', b)
}

function gen_action_area(view, a) {
	gen_action(view, 'area', a)
}

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 area_name(where) {
	return AREAS[where].name
}

function area_tag(where) {
	return "#" + where
}

function block_name(who) {
	if (who === B_EDWARD)
		return game.edward === 1 ? "Edward I" : "Edward II"
	if (who === B_KING)
		return "Scottish King"
	return BLOCKS[who].name
}

function block_owner(who) {
	return BLOCKS[who].owner
}

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

function block_move(who) {
	return BLOCKS[who].move
}

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

function block_is_mortal(who) {
	return BLOCKS[who].mortal
}

function block_initiative(who) {
	return BLOCKS[who].initiative
}

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

function block_fire_power(who, where) {
	let area = AREAS[where]
	let combat = block_printed_fire_power(who)
	if (is_defender(who)) {
		if (block_type(who) === 'nobles' && area.home === block_name(who))
			++combat
		else if (who === B_MORAY && where === AREA_MORAY)
			++combat
	}
	if (game.schiltroms) {
		if (is_scottish_infantry(who) && english_have_no_archers_in_battle(where))
			++combat
	}
	return combat
}

function is_scottish_infantry(who) {
	return block_owner(who) === SCOTLAND && block_type(who) === 'infantry'
}

function is_english_archers(who) {
	return block_owner(who) === ENGLAND && block_type(who) === 'archers'
}

function english_have_no_archers_in_battle(where) {
	for (let b = 0; b < block_count; ++b)
		if (game.location[b] === where && is_english_archers(b) && !is_battle_reserve(b))
			return false
	return true
}

function is_coastal_area(where) {
	return AREAS[where].coastal
}

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

function is_friendly_coastal_area(where) {
	return is_coastal_area(where) && is_friendly_area(where)
}

function is_in_friendly_coastal_area(who) {
	let where = game.location[who]
	if (where && where !== E_BAG && where !== S_BAG)
		return is_friendly_coastal_area(where)
	return false
}

function is_on_map(who) {
	let where = game.location[who]
	if (where !== NOWHERE && where !== E_BAG && where !== S_BAG)
		return true
	return false
}

function count_blocks_in_area(where) {
	let count = 0
	for (let b = 0; b < block_count; ++b)
		if (game.location[b] === where)
			++count
	return count
}

function count_blocks_in_area_excluding(where, exc) {
	let count = 0
	for (let b = 0; b < block_count; ++b)
		if (game.location[b] === where && !exc.includes(b))
			++count
	return count
}

function castle_limit(where) {
	if (game.active === SCOTLAND && is_cathedral_area(where))
		return AREAS[where].limit + 1
	return AREAS[where].limit
}

function is_within_castle_limit(where) {
	return count_blocks_in_area(where) <= castle_limit(where)
}

function is_under_castle_limit(where) {
	return count_blocks_in_area(where) < castle_limit(where)
}

function count_english_nobles() {
	let count = 0
	for (let b = 0; b < block_count; ++b)
		if (block_owner(b) === ENGLAND && block_type(b) === 'nobles')
			if (is_on_map(b))
				++count
	return count
}

function count_scottish_nobles() {
	let count = 0
	for (let b = 0; b < block_count; ++b)
		if (block_owner(b) === SCOTLAND && block_type(b) === 'nobles')
			if (is_on_map(b))
				++count
	if (is_on_map(B_MORAY))
		++count
	return count
}

function find_noble(owner, name) {
	if (owner === ENGLAND)
		return ENGLISH_NOBLES[name]
	return SCOTTISH_NOBLES[name]
}

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) === PID[ENEMY[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)
			++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)
			++count
	return count
}

function is_friendly_area(where) { return count_friendly(where) > 0 && count_enemy(where) === 0 }
function is_enemy_area(where) { return count_friendly(where) === 0 && count_enemy(where) > 0 }
function is_neutral_area(where) { return count_friendly(where) === 0 && count_enemy(where) === 0 }
function is_contested_area(where) { return count_friendly(where) > 0 && count_enemy(where) > 0 }
function is_friendly_or_neutral_area(where) { return is_friendly_area(where) || is_neutral_area(where) }

function have_contested_areas() {
	for (let where = first_map_area; where < area_count; ++where)
		if (is_contested_area(where))
			return true
	return false
}

function count_pinning(where) {
	return count_enemy(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)
			if (!set_has(game.reserves, b))
				++count
	return count
}

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

function can_block_use_border(who, from, to) {
	if (border_type(from, to) === 'major')
		return border_limit(from, to) < 6
	return border_limit(from, to) < 2
}

function can_block_move_to(who, from, to) {
	// No group moves across Anglo-Scottish border
	if (from === AREA_ENGLAND || to === AREA_ENGLAND)
		if (game.moves === 0)
			return false
	if (game.active === SCOTLAND && game.truce === SCOTLAND && to === AREA_ENGLAND)
		return false
	if (can_block_use_border(who, from, to)) {
		if (count_pinning(from) > 0) {
			if (border_was_last_used_by_enemy(from, to))
				return false
		}
		if (game.truce === game.active && is_enemy_area(to))
			return false
		return true
	}
	return false
}

function can_block_move(who) {
	if (!is_on_map(who))
		return false
	if (who === B_NORSE)
		return false
	if (block_owner(who) === game.active && !set_has(game.moved, who)) {
		let from = game.location[who]
		if (from) {
			if (is_pinned(from))
				return false
			for (let to of AREAS[from].exits)
				if (can_block_move_to(who, from, to))
					return true
		}
	}
	return false
}

function can_block_continue(who, from, here) {
	if (here === AREA_ENGLAND)
		return false
	if (is_contested_area(here))
		return false
	if (border_type(from, here) === 'minor')
		return false
	if (game.distance >= block_move(who))
		return false
	for (let to of AREAS[here].exits)
		if (to !== game.last_from && can_block_move_to(who, here, to))
			return true
	return false
}

function can_block_retreat_to(who, to) {
	if (is_friendly_area(to) || is_neutral_area(to)) {
		let from = game.location[who]
		if (block_owner(who) === ENGLAND && from === AREA_ENGLAND)
			return false
		if (block_owner(who) === SCOTLAND && to === AREA_ENGLAND)
			return false
		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_retreat(who) {
	if (block_owner(who) === game.active) {
		if (who === B_NORSE)
			return true
		let from = game.location[who]
		for (let to of AREAS[from].exits)
			if (can_block_retreat_to(who, to))
				return true
	}
	return false
}

function can_block_regroup_to(who, to) {
	if (is_friendly_area(to) || is_neutral_area(to)) {
		let from = game.location[who]
		if (block_owner(who) === ENGLAND && from === AREA_ENGLAND)
			return false
		if (block_owner(who) === SCOTLAND && to === AREA_ENGLAND)
			return false
		if (can_block_use_border(who, from, to))
			return true
	}
	return false
}

function can_block_regroup(who) {
	if (block_owner(who) === game.active) {
		if (who === B_NORSE) {
			for (let to = first_map_area; to < area_count; ++to)
				if (to !== game.where && to !== AREA_ENGLAND && is_friendly_coastal_area(to))
					return true
			return false
		}
		let from = game.location[who]
		for (let to of AREAS[from].exits)
			if (can_block_regroup_to(who, to))
				return true
	}
	return false
}

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

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

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

function swap_blocks(old) {
	let bo = ENEMY[block_owner(old)]
	let b = find_noble(bo, block_name(old))
	game.location[b] = game.location[old]
	game.steps[b] = game.steps[old]
	game.location[old] = NOWHERE
	game.steps[old] = block_max_steps(old)
	return b
}

function disband(who) {
	game.location[who] = block_owner(who) === ENGLAND ? E_BAG : S_BAG
	game.steps[who] = block_max_steps(who)
}

function eliminate_block(who, reason) {
	if (block_type(who) === 'nobles') {
		if (reason === 'retreat') {
			game.turn_log.push([area_tag(game.location[who]), "Captured"])
		} else if (reason === 'combat') {
			game.flash = block_name(who) + " was captured."
			log(block_name(who) + " was captured.")
		} else {
			log(block_name(who) + " was captured.")
		}
	} else {
		if (reason === 'retreat') {
			game.turn_log.push([area_tag(game.location[who]), "Eliminated"])
		} else if (reason === 'combat') {
			game.flash = block_name(who) + " was eliminated."
			log(block_name(who) + " was eliminated.")
		} else {
			if (block_owner(who) === ENGLAND)
				log("English block was eliminated.")
			else
				log("Scottish block was eliminated.")
		}
	}

	// TODO: clean up and check all combinations
	if (who === B_EDWARD) {
		if (reason === 'combat' || reason === 'retreat') {
			if (game.edward === 1) {
				game.edward = 2
				disband(who)
			} else {
				game.location[who] = NOWHERE
				game.victory = "Scotland won because king Edward II has died in battle!"
				game.result = SCOTLAND
			}
		} else {
			disband(who)
		}
	} else if (who === B_KING) {
		if (reason === 'combat' || reason === 'retreat') {
			game.location[who] = NOWHERE
			game.victory = "England won because the Scottish king has died in battle!"
			game.result = ENGLAND
		} else {
			disband(who)
		}
	} else if (block_is_mortal(who) && (reason === 'combat' || reason === 'retreat')) {
		game.location[who] = NOWHERE
	} else if (block_type(who) === 'nobles') {
		who = swap_blocks(who)
		game.steps[who] = 1 // flip at strength 1 if eliminated
		if (reason === 'combat' || reason === 'retreat')
			set_add(game.reserves, who)
	} else {
		disband(who)
	}
}

function reduce_block(who, reason) {
	if (game.steps[who] === 1) {
		eliminate_block(who, reason)
	} 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
}

const CELTIC_BLOCKS = [
	block_index["Ulster Infantry"],
	block_index["Wales Archers"],
	block_index["Wales Infantry"],
]

function celtic_unity_roll(who) {
	let die = roll_d6()
	if (die >= 5) {
		log(block_name(who) + " rolled " + DIE_HIT[die] + " for Celtic unity and returned to the draw pool.")
		disband(who)
	} else {
		log(block_name(who) + " rolled " + DIE_MISS[die] + " for Celtic unity \u2013 no effect.")
	}
}

// SETUP

function reset_blocks() {
	for (let b = 0; b < block_count; ++b) {
		game.steps[b] = block_max_steps(b)
		if (block_type(b) === 'nobles')
			game.location[b] = NOWHERE
		else if (block_owner(b) === ENGLAND)
			game.location[b] = E_BAG
		else
			game.location[b] = S_BAG
	}
}

function deploy_noble(owner, area, name) {
	if (name in block_index) {
		game.location[block_index[name]] = area
	} else {
		let friend = find_noble(owner, name)
		let enemy = find_noble(ENEMY[owner], name)
		game.location[friend] = area
		game.location[enemy] = NOWHERE
	}
}

function deploy_block(area, block) {
	block = block_index[block]
	game.location[block] = area
}

function draw_from_bag(bag, exclude_list) {
	let list = []
	for (let b = 0; b < block_count; ++b) {
		if (exclude_list && exclude_list.includes(b))
			continue
		if (game.location[b] === bag)
			list.push(b)
	}
	if (list.length === 0)
		return NOBODY
	return list[random(list.length)]
}

function deploy_english(count) {
	let list = []
	for (let b = 0; b < block_count; ++b)
		if (game.location[b] === E_BAG)
			list.push(b)
	for (let i = 0; i < count; ++i) {
		let x = random(list.length)
		let b = list[x]
		list.splice(x,1)
		game.location[b] = AREA_ENGLAND
		game.steps[b] = block_max_steps(b)
	}
}

function deploy_off_map(block) {
	block = block_index[block]
	game.location[block] = NOWHERE
}

function setup_braveheart() {
	reset_blocks()

	deploy_noble("England", AREA_BADENOCH, "Comyn")
	deploy_noble("England", AREA_ANGUS, "Angus")
	deploy_noble("England", AREA_ARGYLL, "Argyll")
	deploy_noble("England", AREA_MAR, "Mar")
	deploy_noble("England", AREA_LENNOX, "Lennox")
	deploy_noble("England", AREA_BUCHAN, "Buchan")
	deploy_noble("England", AREA_ROSS, "Ross")
	deploy_noble("England", AREA_ATHOLL, "Atholl")
	deploy_noble("England", AREA_DUNBAR, "Dunbar")
	deploy_noble("England", AREA_MENTIETH, "Mentieth")
	deploy_noble("England", AREA_LANARK, "Steward")

	deploy_block(AREA_LOTHIAN, "Cumbria Infantry")
	deploy_block(AREA_MENTIETH, "Northumber Infantry")

	deploy_english(4)

	deploy_noble("Scotland", AREA_ANNAN, "Bruce")
	deploy_noble("Scotland", AREA_GALLOWAY, "Galloway")

	deploy_block(AREA_FIFE, "Wallace")
	deploy_block(AREA_FIFE, "Douglas")
	deploy_block(AREA_FIFE, "Barclay")
	deploy_block(AREA_MORAY, "Moray")
	deploy_block(AREA_MORAY, "Fraser")
	deploy_block(AREA_STRATHSPEY, "Grant")

	deploy_off_map("King")
	deploy_off_map("French Knights")

	game.scottish_king = false
	game.edward = 1
	game.year = 1297
	game.end_year = 1305
}

function setup_the_bruce() {
	reset_blocks()

	deploy_noble("England", AREA_BADENOCH, "Comyn")
	deploy_noble("England", AREA_ANGUS, "Angus")
	deploy_noble("England", AREA_ARGYLL, "Argyll")
	deploy_noble("England", AREA_BUCHAN, "Buchan")
	deploy_noble("England", AREA_GALLOWAY, "Galloway")
	deploy_noble("England", AREA_ROSS, "Ross")
	deploy_noble("England", AREA_MENTIETH, "Mentieth")
	deploy_noble("England", AREA_LANARK, "Steward")

	deploy_block(AREA_MORAY, "Cumbria Infantry")
	deploy_block(AREA_MENTIETH, "Northumber Infantry")
	deploy_block(AREA_LOTHIAN, "Durham Infantry")
	deploy_block(AREA_LANARK, "Westmor Infantry")

	deploy_english(6)

	deploy_noble("Scotland", AREA_DUNBAR, "Dunbar")
	deploy_noble("Scotland", AREA_LENNOX, "Lennox")
	deploy_noble("Scotland", AREA_ATHOLL, "Atholl")
	deploy_noble("Scotland", AREA_MAR, "Mar")
	deploy_noble("Scotland", AREA_CARRICK, "Bruce")

	deploy_block(AREA_FIFE, "King")
	deploy_block(AREA_FIFE, "Douglas")
	deploy_block(AREA_FIFE, "Barclay")
	deploy_block(AREA_LENNOX, "Campbell")
	deploy_block(AREA_CARRICK, "Lindsay")

	deploy_off_map("Moray")
	deploy_off_map("Wallace")
	deploy_off_map("French Knights")

	game.scottish_king = true
	game.edward = 1
	game.year = 1306
	game.end_year = 1314
}

function setup_campaign() {
	setup_braveheart()
	game.end_year = 1400; /* no limit */
}

// GAME TURN

function start_year() {
	log("")
	log(".h1 Year " + game.year)

	// Deal new cards
	let deck = shuffle_deck()
	game.e_hand = deal_cards(deck, 5)
	game.s_hand = deal_cards(deck, 5)

	start_game_turn()
}

function start_game_turn() {
	game.turn = 6 - game.e_hand.length

	log("")
	log(".h1 Turn " + game.turn + " of Year " + game.year)

	// Reset movement and attack tracking state
	game.truce = false
	reset_border_limits()
	game.last_used = []
	game.attacker = []
	game.reserves = []
	game.moved = []

	goto_card_phase()
}

function end_game_turn() {
	if (count_english_nobles() === 0) {
		game.victory = "Scotland won by controlling all the nobles!"
		game.result = SCOTLAND
	}
	if (count_scottish_nobles() === 0) {
		game.victory = "England won by controlling all the nobles!"
		game.result = ENGLAND
	}
	if (game.victory)
		return goto_game_over()

	if (game.e_hand.length > 0)
		start_game_turn()
	else
		goto_winter_turn()
}

// CARD PHASE

function goto_card_phase() {
	game.e_card = 0
	game.s_card = 0
	game.show_cards = 0
	game.state = 'play_card'
	game.active = BOTH
}

function resume_play_card() {
	if (game.s_card > 0 && game.e_card > 0)
		reveal_cards()
	else if (game.s_card > 0)
		game.active = ENGLAND
	else if (game.e_card > 0)
		game.active = SCOTLAND
	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 === ENGLAND) {
			if (game.e_card) {
				view.prompt = "Waiting for Scotland to play a card."
			} else {
				view.prompt = "Play a card."
				for (let c of game.e_hand)
					gen_action(view, 'play', c)
			}
		}
		if (current === SCOTLAND) {
			if (game.s_card) {
				view.prompt = "Waiting for England to play a card."
			} else {
				view.prompt = "Play a card."
				for (let c of game.s_hand)
					gen_action(view, 'play', c)
			}
		}
	},
	play: function (card, current) {
		if (current === ENGLAND) {
			remove_from_array(game.e_hand, card)
			game.e_card = card
		}
		if (current === SCOTLAND) {
			remove_from_array(game.s_hand, card)
			game.s_card = card
		}
		resume_play_card()
	},
	undo: function (_, current) {
		if (current === ENGLAND) {
			game.e_hand.push(game.e_card)
			game.e_card = 0
		}
		if (current === SCOTLAND) {
			game.s_hand.push(game.s_card)
			game.s_card = 0
		}
		resume_play_card()
	}
}

function reveal_cards() {
	log("")
	log("England played " + CARDS[game.e_card].name + ".")
	log("Scotland played " + CARDS[game.s_card].name + ".")
	game.show_cards = 1

	let ec = CARDS[game.e_card]
	let sc = CARDS[game.s_card]

	if (ec.event && sc.event) {
		log("Two events played at the same time. The year will end after this turn.")
		game.e_hand.length = 0
		game.s_hand.length = 0
	}

	if (ec.event) {
		game.p1 = ENGLAND
		game.p2 = SCOTLAND
	} else if (sc.event) {
		game.p1 = SCOTLAND
		game.p2 = ENGLAND
	} else if (sc.moves > ec.moves) {
		game.p1 = SCOTLAND
		game.p2 = ENGLAND
	} else {
		game.p1 = ENGLAND
		game.p2 = SCOTLAND
	}

	game.active = game.p1
	start_player_turn()
}

function start_player_turn() {
	log("")
	log(".h2 " + game.active)
	reset_border_limits()
	let ec = CARDS[game.e_card]
	let sc = CARDS[game.s_card]
	if (game.active === ENGLAND && ec.event)
		goto_event(ec.event)
	else if (game.active === SCOTLAND && sc.event)
		goto_event(sc.event)
	else if (game.active === ENGLAND)
		goto_move_phase(ec.moves)
	else if (game.active === SCOTLAND)
		goto_move_phase(sc.moves)
}

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

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

// CORONATION

function can_crown_bruce() {
	return game.location[B_WALLACE] === NOWHERE && game.location[B_BRUCE_S] === AREA_FIFE
}

function can_crown_comyn() {
	return game.location[B_WALLACE] === NOWHERE && game.location[B_COMYN_S] === AREA_FIFE
}

function can_crown_balliol() {
	return game.year >= 1301 && is_on_map(B_FRENCH_KNIGHTS)
}

function goto_event(event) {
	if (game.active === SCOTLAND && !game.scottish_king &&
		(can_crown_bruce() || can_crown_comyn() || can_crown_balliol())) {
		game.state = 'coronation_event'
		game.event = event
	} else {
		goto_event_card(event)
	}
}

states.coronation_event = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to crown a king."
		view.prompt = "Play event or crown a king?"
		gen_action(view, 'play_event')
		if (can_crown_bruce())
			gen_action(view, 'crown_bruce')
		if (can_crown_comyn())
			gen_action(view, 'crown_comyn')
		if (can_crown_balliol())
			gen_action(view, 'return_of_the_king')
	},
	crown_bruce: function () {
		log("Bruce was crowned King!")
		game.scottish_king = true
		game.location[B_KING] = AREA_FIFE
		game.steps[B_KING] = block_max_steps(B_KING)
		defect_comyn_nobles()
	},
	crown_comyn: function () {
		log("Comyn was crowned King!")
		game.scottish_king = true
		game.location[B_KING] = AREA_FIFE
		game.steps[B_KING] = block_max_steps(B_KING)
		defect_bruce_nobles()
	},
	return_of_the_king: function () {
		log("Return of the King!")
		game.scottish_king = true
		game.location[B_KING] = game.location[B_FRENCH_KNIGHTS]
		game.steps[B_KING] = block_max_steps(B_KING)
		defect_bruce_nobles()
	},
	play_event: function () {
		let event = game.event
		delete game.event
		goto_event_card(event)
	},
}

function defect_bruce_nobles() {
	defect_nobles([ "Bruce", "Mar", "Lennox", "Atholl", "Dunbar", "Mentieth", "Steward" ])
}

function defect_comyn_nobles() {
	defect_nobles([ "Comyn", "Angus", "Argyll", "Buchan", "Galloway", "Ross" ])
}

function defect_nobles(list) {
	for (let name of list) {
		let who = find_noble(game.active, name)
		if (is_on_map(who)) {
			let where = game.location[who]
			log(name + " defected.")
			who = swap_blocks(who)
			if (is_contested_area(where))
				set_attacker(where, block_owner(who))
		}
	}
	resume_coronation()
}

function resume_coronation() {
	if (have_contested_areas()) {
		game.active = game.p1
		game.state = 'coronation_battles'
	} else {
		game.active = SCOTLAND
		end_player_turn()
	}
}

states.coronation_battles = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to choose a battle."
		view.prompt = "Coronation: Choose the next battle to fight!"
		for (let where = first_map_area; where < area_count; ++where)
			if (is_contested_area(where))
				gen_action_area(view, where)
	},
	area: function (where) {
		start_battle(where, 'coronation')
	},
}

// EVENTS

function goto_event_card(event) {
	switch (event) {
	case 'herald': goto_herald(); break
	case 'pillage': goto_pillage(); break
	case 'sea_move': goto_sea_move(); break
	case 'truce': goto_truce(); break
	case 'victuals': goto_victuals(); break
	}
}

function goto_truce() {
	log("Truce is in effect!")
	game.truce = ENEMY[game.active]
	end_player_turn()
}

function goto_herald() {
	game.state = 'herald'
}

function is_enemy_noble(who) {
	return is_on_map(who) && block_type(who) === 'nobles' && block_owner(who) === ENEMY[game.active]
}

states.herald = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to choose a noble."
		view.prompt = "Herald: Name an enemy noble to try to convert to your side."
		gen_action(view, 'pass')
		for (let b = 0; b < block_count; ++b)
			if (is_enemy_noble(b))
				gen_action(view, 'noble', block_name(b))
	},
	noble: function (name) {
		let who = find_noble(ENEMY[game.active], name)
		let die = roll_d6()
		if (die <= 4) {
			log("Herald roll " + DIE_HIT[die] + " converted " + name + ".")
			let where = game.location[who]
			who = swap_blocks(who)
			if (is_contested_area(where)) {
				set_attacker(where, game.active)
				start_battle(where, 'herald')
				return
			}
		} else {
			log("Herald roll " + DIE_MISS[die] + " failed to convert " + name + ".")
		}
		end_player_turn()
	},
	pass: function () {
		end_player_turn()
	},
}

function goto_victuals() {
	game.victuals = 3
	game.where = NOWHERE
	game.state = 'victuals'
	game.turn_log = []
	clear_undo()
}

states.victuals = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to build."
		gen_action_undo(view)
		let done = true
		if (game.victuals > 0) {
			for (let b = 0; b < block_count; ++b) {
				if (is_on_map(b) && block_owner(b) === game.active) {
					if (game.steps[b] < block_max_steps(b)) {
						if (!game.where || game.location[b] === game.where) {
							gen_action_block(view, b)
							done = false
						}
					}
				}
			}
		}
		if (done)
			view.prompt = "Victuals: Distribute three steps among friendly blocks in one group \u2014 done."
		else
			view.prompt = "Victuals: Distribute three steps among friendly blocks in one group."
		gen_action(view, 'end_builds')
	},
	block: function (who) {
		push_undo()
		game.where = game.location[who]
		game.turn_log.push([area_tag(game.where)])
		++game.steps[who]
		--game.victuals
	},
	end_builds: function () {
		print_turn_log("victualed")
		clear_undo()
		delete game.victuals
		game.where = NOWHERE
		end_player_turn()
	},
	undo: pop_undo
}

function goto_pillage() {
	game.state = 'pillage'
	game.turn_log = []
}

states.pillage = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to pillage."
		view.prompt = "Pillage: Pillage one enemy group adjacent to a friendly group."
		gen_action(view, 'pass')
		for (let from = first_map_area; from < area_count; ++from) {
			if (is_friendly_area(from)) {
				for (let to of AREAS[from].exits)
					if (is_contested_area(to) || is_enemy_area(to))
						gen_action_area(view, to)
			}
		}
	},
	area: function (where) {
		game.where = where
		game.pillage = 2
		game.active = ENEMY[game.active]
		game.state = 'pillage_hits'
	},
	pass: function () {
		end_player_turn()
	},
}

function pillage_victims() {
	function is_candidate(b) {
		return block_owner(b) === game.active && game.location[b] === game.where
	}
	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)
			list.push(b)
	return list
}

states.pillage_hits = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to apply pillage hits."
		view.prompt = "Pillage: Apply two hits in " + area_name(game.where) + "."
		for (let b of pillage_victims())
			gen_action_block(view, b)
	},
	block: function (who) {
		--game.pillage
		reduce_block(who, 'pillage')
		if (game.pillage === 0 || pillage_victims().length === 0) {
			game.active = ENEMY[game.active]
			game.state = 'pillage_builds'
			game.pillage = 2 - game.pillage
			game.from = game.where
			game.where = NOWHERE
		}
	},
}

states.pillage_builds = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to apply pillage builds."
		gen_action_undo(view)
		let done = true
		if (game.pillage > 0) {
			if (game.where) {
				for (let b = 0; b < block_count; ++b) {
					if (block_owner(b) === game.active && game.location[b] === game.where) {
						if (game.steps[b] < block_max_steps(b)) {
							gen_action_block(view, b)
							done = false
						}
					}
				}
			} else {
				for (let to of AREAS[game.from].exits) {
					for (let b = 0; b < block_count; ++b) {
						if (block_owner(b) === game.active && game.location[b] === to) {
							if (game.steps[b] < block_max_steps(b)) {
								gen_action_block(view, b)
								done = false
							}
						}
					}
				}
			}
		}
		if (done) {
			view.prompt = "Pillage: Add pillaged steps to friendly blocks in the pillaging group \u2014 done"
			gen_action(view, 'end_pillage')
		} else {
			view.prompt = "Pillage: Add pillaged steps to friendly blocks in the pillaging group."
		}
	},
	block: function (who) {
		push_undo()
		game.where = game.location[who]
		game.turn_log.push([area_tag(game.from), area_tag(game.where)])
		++game.steps[who]
		--game.pillage
		// TODO: auto-end pillage builds?
		// if (game.pillage === 0) end_pillage(game.from)
	},
	end_pillage: function () {
		clear_undo()
		while (game.pillage > 0) {
			--game.pillage
			game.turn_log.push([area_tag(game.from)])
		}
		end_pillage(game.from)
	},
	undo: pop_undo
}

function end_pillage(where) {
	print_turn_log("pillaged")
	game.from = NOWHERE
	game.where = NOWHERE
	delete game.pillage
	if (is_contested_area(where)) {
		set_attacker(where, game.active)
		start_battle(where, 'pillage')
	} else {
		end_player_turn()
	}
}

function goto_sea_move() {
	game.moves = 2
	game.from = NOWHERE
	game.where = NOWHERE
	game.state = 'sea_move'
	game.turn_log = []
	clear_undo()
}

states.sea_move = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to sea move."
		view.prompt = "Sea Move: Move one or two blocks from one coastal area to one other friendly coastal area."
		gen_action_undo(view)
		gen_action(view, 'end_move_phase')
		if (game.moves > 0) {
			for (let b = 0; b < block_count; ++b) {
				if (b === B_NORSE)
					continue
				if (is_in_friendly_coastal_area(b) && block_owner(b) === game.active)
					if (!game.from || game.location[b] === game.from)
						gen_action_block(view, b)
			}
		}
	},
	block: function (who) {
		push_undo()
		game.who = who
		game.state = 'sea_move_to'
	},
	end_move_phase: function () {
		print_turn_log("sea moved")
		clear_undo()
		game.moves = 0
		game.from = NOWHERE
		game.where = NOWHERE
		end_player_turn()
	},
	undo: pop_undo
}

states.sea_move_to = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to sea move."
		view.prompt = "Sea Move: Move one or two blocks from one coastal area to one other friendly coastal area."
		gen_action_undo(view)
		gen_action_block(view, game.who)
		if (game.where) {
			gen_action_area(view, game.where)
		} else {
			let from = game.location[game.who]
			for (let to = first_map_area; to < area_count; ++to)
				if (to !== from && is_friendly_coastal_area(to))
					gen_action_area(view, to)
		}
	},
	area: function (to) {
		if (!game.from)
			game.from = game.location[game.who]
		game.turn_log.push([area_tag(game.from), area_tag(to)])
		game.location[game.who] = to
		set_add(game.moved, game.who)
		game.where = to
		game.who = NOBODY
		--game.moves
		game.state = 'sea_move'
	},
	block: pop_undo,
	undo: pop_undo
}

// MOVE PHASE

function get_attacker(x) {
	return UNPID[map_get(game.attacker, x, 0)]
}

function set_attacker(x, who) {
	return map_set(game.attacker, x, PID[who])
}

function main_border(to) {
	return map_get(game.main_border, to, 0)
}

function main_origin(to) {
	return map_get(game.main_origin, to, 0)
}

function set_main_border(to, x) {
	map_set(game.main_border, to, x)
}

function set_main_origin(to, x) {
	map_set(game.main_origin, to, x)
}

function goto_move_phase(moves) {
	game.state = 'move_who'
	game.moves = moves
	game.activated = []
	game.main_origin = []
	game.main_border = []
	game.turn_log = []
	clear_undo()
}

states.move_who = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to move."
		view.prompt = "Choose an army to move. " + game.moves + "MP left."
		gen_action_undo(view)
		gen_action(view, 'end_move_phase')
		for (let b = 0; b < block_count; ++b) {
			if (b === B_NORSE && game.active === SCOTLAND && is_on_map(B_NORSE)) {
				if (!set_has(game.moved, b) && game.moves > 0 && !is_pinned(game.location[B_NORSE]))
					gen_action_block(view, B_NORSE)
			}
			if (can_block_move(b)) {
				if (game.moves === 0) {
					let from = game.location[b]
					if (game.activated.includes(from))
						gen_action_block(view, b)
				} else {
					gen_action_block(view, b)
				}
			}
		}
	},
	block: function (who) {
		push_undo()
		game.who = who
		game.state = 'move_where'
		game.origin = game.location[who]
		game.last_from = NOWHERE
		game.distance = 0
	},
	end_move_phase: function () {
		clear_undo()
		game.moves = 0
		print_turn_log("moved")
		end_player_turn()
	},
	undo: pop_undo
}

function move_block(who, from, to) {
	game.location[who] = to
	set_border_limit(from, to, border_limit(from, to) + 1)
	game.distance ++
	if (is_contested_area(to)) {
		map_set(game.last_used, border_id(from, to), PID[game.active])
		if (!get_attacker(to)) {
			set_attacker(to, game.active)
			set_main_border(to, from)
			set_main_origin(to, game.origin)
			return ATTACK_MARK
		} else {
			if (get_attacker(to) !== game.active || main_border(to) !== from || main_origin(to) !== game.origin) {
				set_add(game.reserves, who)
				return RESERVE_MARK
			} else {
				return ATTACK_MARK
			}
		}
	}
	return false
}

states.move_where = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to move."
		view.prompt = "Move " + block_name(game.who) + "."
		gen_action_undo(view)
		gen_action_block(view, game.who)
		let from = game.location[game.who]
		if (game.who === B_NORSE) {
			for (let to = first_map_area; to < area_count; ++to)
				if (to !== from && to !== AREA_ENGLAND && is_coastal_area(to))
					if (game.truce !== game.active || !is_enemy_area(to))
						gen_action_area(view, to)
		} else {
			if (game.distance > 0)
				gen_action_area(view, from)
			for (let to of AREAS[from].exits) {
				if (to !== game.last_from && can_block_move_to(game.who, from, to))
					gen_action_area(view, 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.who === B_NORSE) {
			log("The Norse moved by sea.")
			game.location[game.who] = to
			set_add(game.moved, game.who)
			if (is_contested_area(to)) {
				if (!get_attacker(to)) {
					game.turn_log.push([area_tag(from), area_tag(to) + ATTACK_MARK + " (Norse)"])
					set_attacker(to, game.active)
				} else {
					game.turn_log.push([area_tag(from), area_tag(to) + RESERVE_MARK + " (Norse)"])
					set_add(game.reserves, game.who)
				}
			} else {
				game.turn_log.push([area_tag(from), area_tag(to) + " (Norse)"])
			}
			--game.moves
			game.who = NOBODY
			game.state = 'move_who'
		} else {
			set_add(game.moved, game.who)
			if (game.distance === 0)
				game.move_buf = [ area_tag(from) ]
			let mark = move_block(game.who, from, to)
			if (mark)
				game.move_buf.push(area_tag(to) + mark)
			else
				game.move_buf.push(area_tag(to))
			game.last_from = from
			if (!can_block_continue(game.who, from, to))
				end_move()
		}
	},
	undo: pop_undo
}

function end_move() {
	if (game.distance > 0) {
		let to = game.location[game.who]
		if (game.origin === AREA_ENGLAND || to === AREA_ENGLAND) {
			log(game.active + " crossed the Anglo-Scottish border.")
			game.moves --
		} else if (!game.activated.includes(game.origin)) {
			log(game.active + " activated " + area_tag(game.origin) + ".")
			game.activated.push(game.origin)
			game.moves --
		}
		game.turn_log.push(game.move_buf)
	}
	delete game.move_buf
	game.who = NOBODY
	game.distance = 0
	game.origin = NOWHERE
	game.last_from = NOWHERE
	game.state = 'move_who'
}

// BATTLE PHASE

function bring_on_reserves() {
	for (let b = 0; b < block_count; ++b)
		if (game.location[b] === game.where)
			set_delete(game.reserves, b)
}

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

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_map_area; where < area_count; ++where)
			if (is_contested_area(where))
				gen_action_area(view, where)
	},
	area: function (where) {
		start_battle(where, 'battle')
	},
}

function print_retreat_summary() {
	if (game.turn_log && game.turn_log.length > 0)
		print_turn_log_no_active("Retreated from " + area_tag(game.where) + ":")
}

function start_battle(where, reason) {
	game.battle_active = game.active
	game.battle_reason = reason
	game.flash = ""
	log("")
	if (reason !== 'battle')
		log(".h3 Defection battle in " + area_tag(where))
	else
		log(".h3 Battle in " + area_tag(where))
	game.where = where
	game.battle_round = 0
	game.state = 'battle_round'
	next_battle_round()
}

function end_battle() {
	print_retreat_summary()

	bring_on_reserves()

	game.flash = ""
	game.battle_round = 0
	reset_border_limits()
	game.moved = []

	game.active = get_attacker(game.where)
	let victor = game.active
	if (is_contested_area(game.where))
		victor = ENEMY[game.active]
	else if (is_enemy_area(game.where))
		victor = ENEMY[game.active]
	log(victor + " won the battle in " + area_tag(game.where) + "!")

	goto_retreat()
}

function next_battle_round() {
	print_retreat_summary()
	switch (game.battle_round) {
	case 0: return goto_battle_round(1)
	case 1: return goto_battle_round(2)
	case 2: return goto_battle_round(3)
	case 3: return end_battle()
	}
}

function goto_battle_round(new_battle_round) {
	game.battle_round = new_battle_round
	game.turn_log = []

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

	reset_border_limits()
	game.moved = []

	if (game.battle_round === 1) {
		for (let b of CELTIC_BLOCKS)
			if (game.location[b] === game.where && !is_battle_reserve(b))
				celtic_unity_roll(b)
	}

	if (game.battle_round === 2) {
		if (count_defenders() === 0) {
			log("Defending main force was eliminated.")
			log("Battlefield control changed.")
			set_attacker(game.where, ENEMY[get_attacker(game.where)])
		} else if (count_attackers() === 0) {
			log("Attacking main force was eliminated.")
		}
		for (let b of CELTIC_BLOCKS)
			if (game.location[b] === game.where && is_battle_reserve(b))
				celtic_unity_roll(b)
		bring_on_reserves()
	}

	if (game.battle_round === 3) {
		bring_on_reserves()
	}

	resume_battle()
}

function resume_battle() {
	if (game.victory)
		return goto_game_over()

	if (is_friendly_area(game.where) || is_enemy_area(game.where))
		return end_battle()

	if (count_attackers() === 0 || count_defenders() === 0)
		return next_battle_round()

	game.state = 'battle_round'
	pump_battle_step()
}

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)) {
			if (block_initiative(b) === ci) {
				if (!output)
					output = []
				output.push(b)
			}
		}
	}
	return output
}

function battle_step(active, initiative, candidate) {
	game.battle_list = filter_battle_blocks(initiative, candidate)
	if (game.battle_list) {
		if (game.active !== active) {
			game.active = active
			if (game.hits > 0) {
				goto_battle_hits()
				return true
			}
		}
		return true
	}
	return false
}

function pump_battle_step() {
	let attacker = get_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 (game.hits > 0) {
		game.active = ENEMY[game.active]
		return goto_battle_hits()
	}

	next_battle_round()
}

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 = "Fire, retreat, or pass with an army."
		for (let b of game.battle_list) {
			gen_action_block(view, b)
			gen_action_battle(view, 'battle_fire', b)
			gen_action_battle(view, 'battle_pass', b)
			if (can_block_retreat(b))
				gen_action_battle(view, 'battle_retreat', b)
		}
		if (game.hits > 0)
			gen_action(view, 'assign')
	},
	assign: function () {
		game.active = ENEMY[game.active]
		if (game.hits === 1)
			game.flash = `Inflicted 1 hit.`
		else
			game.flash = `Inflicted ${game.hits} hits.`
		goto_battle_hits()
	},
	block: function (who) {
		fire_with_block(who)
	},
	battle_fire: function (who) {
		fire_with_block(who)
	},
	battle_retreat: function (who) {
		retreat_with_block(who)
	},
	battle_pass: function (who) {
		pass_with_block(who)
	}
}

function retreat_with_block(b) {
	game.who = b
	game.state = 'retreat_in_battle'
}

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

function count_enemy_hp_in_battle() {
	let is_candidate = (game.active === get_attacker(game.where)) ? is_defender : is_attacker
	let n = 0
	for (let b = 0; b < block_count; ++b)
		if (is_candidate(b))
			n += game.steps[b]
	return n
}

function must_apply_hits() {
	if (game.immediate)
		return game.hits > 0
	return game.hits >= count_enemy_hp_in_battle()
}

function fire_with_block(b) {
	set_add(game.moved, b)
	let steps = game.steps[b]
	let fire = block_fire_power(b, game.where)
	let printed_fire = block_printed_fire_power(b)
	let name = block_name(b) + " " + BLOCKS[b].combat
	if (fire > printed_fire)
		name += "+" + (fire - printed_fire)

	let rolls = []
	let hits = 0
	for (let i = 0; i < steps; ++i) {
		let die = roll_d6()
		if (die <= fire) {
			rolls.push(DIE_HIT[die])
			++hits
		} else {
			rolls.push(DIE_MISS[die])
		}
	}
	game.hits += hits

	log_battle(name + " fired " + rolls.join("") + ".")

	if (game.immediate) {
		game.flash = name + " fired " + rolls.join(" ")
		if (hits === 0)
			game.flash += " and missed."
		else if (hits === 1)
			game.flash += " and scored 1 hit."
		else
			game.flash += " and scored " + hits + " hits."
	} else {
		game.flash = name + " fired " + rolls.join(" ")
		if (game.hits === 0)
			game.flash += "."
		else if (game.hits === 1)
			game.flash += " for a total of 1 hit."
		else if (game.hits > 1)
			game.flash += " for a total of " + game.hits + " hits."
	}

	if (must_apply_hits()) {
		game.active = ENEMY[game.active]
		goto_battle_hits()
	} else {
		resume_battle()
	}
}

function goto_battle_hits() {
	game.battle_list = list_victims(game.active)

	if (game.autohit) {
		let n = 0
		while (game.hits >= game.battle_list.length && game.battle_list.length > 0) {
			while (game.battle_list.length > 0) {
				let who = game.battle_list.pop()
				log_battle(block_name(who) + " took a hit.")
				reduce_block(who, 'combat')
				game.hits--
				++n
			}
			if (game.hits > 0)
				game.battle_list = list_victims(game.active)
		}
		if (n > 0)
			game.flash += ` Assigned ${n}.`
	}

	if (game.battle_list.length === 0) {
		game.hits = 0
		resume_battle()
	} else {
		game.state = 'battle_hits'
	}
}

function apply_hit(who) {
	game.flash = block_name(who) + " took a hit."
	log_battle(block_name(who) + " took a hit.")
	reduce_block(who, 'combat')
	game.hits--
	if (game.victory)
		goto_game_over()
	else if (game.hits === 0)
		resume_battle()
	else {
		game.battle_list = list_victims(game.active)
		if (game.battle_list.length === 0) {
			game.hits = 0
			resume_battle()
		} else {
			game.flash += " " + game.hits + (game.hits === 1 ? " hit left." : " hits left.")
		}
	}
}

function list_victims(p) {
	let is_candidate = (p === get_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)
			list.push(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_block(view, b)
			gen_action_battle(view, 'battle_hit', b)
		}
	},
	block: function (who) {
		apply_hit(who)
	},
	battle_hit: function (who) {
		apply_hit(who)
	},
}

function goto_retreat() {
	game.active = get_attacker(game.where)
	if (is_contested_area(game.where)) {
		game.state = 'retreat'
		game.turn_log = []
		clear_undo()
	} else {
		goto_regroup()
	}
}

states.retreat = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to retreat."
		view.prompt = "Retreat: Choose an army to move."
		gen_action_undo(view)
		let can_retreat = false
		for (let b = 0; b < block_count; ++b) {
			if (game.location[b] === game.where && can_block_retreat(b)) {
				gen_action_block(view, b)
				can_retreat = true
			}
		}
		if (!is_contested_area(game.where) || !can_retreat)
			gen_action(view, 'end_retreat')
	},
	end_retreat: function () {
		clear_undo()
		for (let b = 0; b < block_count; ++b)
			if (game.location[b] === game.where && block_owner(b) === game.active)
				eliminate_block(b, 'retreat')
		if (game.victory)
			return goto_game_over()
		print_turn_log("retreated")
		goto_regroup()
	},
	block: function (who) {
		push_undo()
		game.who = who
		game.state = 'retreat_to'
	},
	undo: pop_undo
}

states.retreat_to = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to retreat."
		gen_action_undo(view)
		gen_action_block(view, game.who)
		let can_retreat = false
		if (game.who === B_NORSE) {
			view.prompt = "Retreat: Move the army to a friendly coastal area."
			for (let to = first_map_area; to < area_count; ++to) {
				if (to !== game.where && to !== AREA_ENGLAND && is_friendly_coastal_area(to)) {
					gen_action_area(view, to)
					can_retreat = true
				}
			}
		} else {
			view.prompt = "Retreat: Move the army to a friendly or neutral area."
			for (let to of AREAS[game.where].exits) {
				if (can_block_retreat_to(game.who, to)) {
					gen_action_area(view, to)
					can_retreat = true
				}
			}
		}
		if (!can_retreat)
			gen_action(view, 'eliminate')
	},
	area: function (to) {
		let from = game.where
		if (game.who === B_NORSE) {
			game.turn_log.push([area_tag(from), area_tag(to) + " (Norse)"])
			game.location[game.who] = to
		} else {
			game.turn_log.push([area_tag(from), area_tag(to)])
			move_block(game.who, game.where, to)
		}
		game.who = NOBODY
		game.state = 'retreat'
	},
	eliminate: function () {
		eliminate_block(game.who, 'retreat')
		if (game.victory)
			return goto_game_over()
		game.who = NOBODY
		game.state = 'retreat'
	},
	block: pop_undo,
	undo: pop_undo
}

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_block(view, game.who)
		if (game.who === B_NORSE) {
			view.prompt = "Retreat: Move the army to a friendly coastal area."
			for (let to = first_map_area; to < area_count; ++to)
				if (to !== game.where && to !== AREA_ENGLAND && is_friendly_coastal_area(to))
					gen_action_area(view, to)
		} else {
			view.prompt = "Retreat: Move the army to a friendly or neutral area."
			for (let to of AREAS[game.where].exits)
				if (can_block_retreat_to(game.who, to))
					gen_action_area(view, to)
		}
	},
	area: function (to) {
		game.turn_log.push([game.active, area_tag(to)])
		if (game.who === B_NORSE) {
			game.flash = "Norse retreated to " + area_name(to) + "."
			log_battle("Norse retreated to " + area_tag(to) + ".")
			game.location[game.who] = to
		} else {
			game.flash = block_name(game.who) + " retreated."
			log_battle(game.flash)
			move_block(game.who, game.where, to)
		}
		game.who = NOBODY
		resume_battle()
	},
	block: function () {
		game.who = NOBODY
		resume_battle()
	},
	undo: function () {
		game.who = NOBODY
		resume_battle()
	}
}

function goto_regroup() {
	game.active = get_attacker(game.where)
	if (is_enemy_area(game.where))
		game.active = ENEMY[game.active]
	game.state = 'regroup'
	game.turn_log = []
	clear_undo()
}

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 && can_block_regroup(b))
				gen_action_block(view, b)
	},
	block: function (who) {
		push_undo()
		game.who = who
		game.state = 'regroup_to'
	},
	end_regroup: function () {
		print_turn_log("regrouped")
		set_attacker(game.where, "") // XXX ???
		game.where = NOWHERE
		clear_undo()
		game.active = game.battle_active
		delete game.battle_active
		if (game.battle_reason === 'herald') {
			delete game.battle_reason
			game.last_used = []
			end_player_turn()
		} else if (game.battle_reason === 'pillage') {
			delete game.battle_reason
			game.last_used = []
			end_player_turn()
		} else if (game.battle_reason === 'coronation') {
			delete game.battle_reason
			game.last_used = []
			resume_coronation()
		} else {
			delete game.battle_reason
			goto_battle_phase()
		}
	},
	undo: pop_undo
}

states.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 neutral area."
		gen_action_undo(view)
		gen_action_block(view, game.who)
		if (game.who === B_NORSE) {
			for (let to = first_map_area; to < area_count; ++to)
				if (to !== game.where && to !== AREA_ENGLAND && is_friendly_coastal_area(to))
					gen_action_area(view, to)
		} else {
			for (let to of AREAS[game.where].exits)
				if (can_block_regroup_to(game.who, to))
					gen_action_area(view, to)
		}
	},
	area: function (to) {
		let from = game.where
		if (game.who === B_NORSE) {
			game.turn_log.push([area_tag(from), area_tag(to) + " (Norse)"])
			game.location[game.who] = to
		} else {
			game.turn_log.push([area_tag(from), area_tag(to)])
			move_block(game.who, game.where, to)
		}
		game.who = NOBODY
		game.state = 'regroup'
	},
	block: pop_undo,
	undo: pop_undo
}

// BORDER RAIDS

function count_non_noble_english_blocks_on_map() {
	let count = 0
	for (let b = 0; b < block_count; ++b)
		if (block_owner(b) === ENGLAND && block_type(b) !== 'nobles')
			if (is_on_map(b))
				++count
	return count
}

function goto_border_raids() {
	game.active = ENGLAND
	if (is_enemy_area(AREA_ENGLAND)) {
		log("Scotland raided in England.")
		if (count_non_noble_english_blocks_on_map() > 0) {
			game.state = 'border_raids'
		} else {
			log("England had no non-noble blocks in play.")
			end_game_turn()
		}
	} else {
		end_game_turn()
	}
}

states.border_raids = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for England to choose a border raid victim."
		view.prompt = "Border Raids: Eliminate a non-Noble block."
		for (let b = 0; b < block_count; ++b)
			if (block_owner(b) === ENGLAND && block_type(b) !== 'nobles')
				if (is_on_map(b))
					gen_action_block(view, b)
	},
	block: function (who) {
		eliminate_block(who, 'border_raids')
		end_game_turn()
	},
}

// WINTERING

function goto_winter_turn() {
	game.moved = []
	log("")
	log(".h1 Winter of " + game.year)
	log("")
	english_nobles_go_home()
}

function is_bruce(who) {
	return who === B_BRUCE_E || who === B_BRUCE_S
}

function is_comyn(who) {
	return who === B_COMYN_E || who === B_COMYN_S
}

function find_noble_home(who) {
	for (let where = first_map_area; where < area_count; ++where)
		if (AREAS[where].home === block_name(who))
			return where
	return NOWHERE
}

function go_home_to(who, home, defected = false) {
	let name = block_name(who)
	let from = game.location[who]
	if (from !== home) {
		game.location[who] = home
		if (is_contested_area(home)) {
			who = swap_blocks(who)
			defected = true
		}
		if (defected)
			game.turn_log.push([name, area_tag(home) + " \u2727"])
		else
			game.turn_log.push([name, area_tag(home)])
	}
}

function go_home(who) {
	go_home_to(who, find_noble_home(who))
}

function english_nobles_go_home() {
	game.turn_log = []
	game.active = ENGLAND
	for (let b = 0; b < block_count; ++b) {
		if (block_owner(b) === ENGLAND && block_type(b) === 'nobles' && game.location[b])
			if (!is_bruce(b) && !is_comyn(b))
				go_home(b)
	}

	game.going_home = ENGLAND
	game.bruce_home = false
	game.comyn_home = false
	goto_e_bruce()
}

function scottish_nobles_go_home() {
	game.turn_log = []
	game.active = SCOTLAND
	for (let b = 0; b < block_count; ++b) {
		if (block_owner(b) === SCOTLAND && block_type(b) === 'nobles' && game.location[b])
			if (!is_bruce(b) && !is_comyn(b))
				go_home(b)
	}
	game.going_home = SCOTLAND
	goto_s_bruce()
}

function goto_e_bruce() {
	game.who = B_BRUCE_E
	if (game.location[B_BRUCE_E] && !game.bruce_home)
		send_bruce_home()
	else
		end_bruce()
}

function goto_s_bruce() {
	game.who = B_BRUCE_S
	if (game.location[B_BRUCE_S] && !game.bruce_home)
		send_bruce_home()
	else
		end_bruce()
}

function send_bruce_home() {
	game.bruce_home = true
	let annan = is_friendly_or_neutral_area(AREA_ANNAN)
	let carrick = is_friendly_or_neutral_area(AREA_CARRICK)
	if (annan && !carrick) {
		go_home_to(game.who, AREA_ANNAN)
		game.who = NOBODY
		return end_bruce()
	}
	if (carrick && !annan) {
		go_home_to(game.who, AREA_CARRICK)
		game.who = NOBODY
		return end_bruce()
	}
	if (!annan && !carrick) {
		game.bruce_defected = true
		game.active = ENEMY[game.active]
		game.who = swap_blocks(game.who)
	} else {
		game.bruce_defected = false
	}
	game.state = 'bruce'
}

states.bruce = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to move Bruce to one of his home areas."
		view.prompt = "Nobles go Home: Move Bruce to one of his home areas."
		gen_action_area(view, AREA_ANNAN)
		gen_action_area(view, AREA_CARRICK)
	},
	area: function (to) {
		go_home_to(game.who, to, game.bruce_defected)
		game.who = NOBODY
		end_bruce()
	},
}

function end_bruce() {
	game.who = NOBODY
	game.active = game.going_home
	delete game.bruce_defected
	if (game.going_home === ENGLAND)
		goto_e_comyn()
	else
		goto_s_comyn()
}

function goto_e_comyn() {
	game.who = B_COMYN_E
	if (game.location[B_COMYN_E] && !game.comyn_home)
		send_comyn_home()
	else
		end_comyn()
}

function goto_s_comyn() {
	game.who = B_COMYN_S
	if (game.location[B_COMYN_S] && !game.comyn_home)
		send_comyn_home()
	else
		end_comyn()
}

function send_comyn_home() {
	game.comyn_home = true
	let badenoch = is_friendly_or_neutral_area(AREA_BADENOCH)
	let lochaber = is_friendly_or_neutral_area(AREA_LOCHABER)
	if (badenoch && !lochaber) {
		go_home_to(game.who, AREA_BADENOCH)
		game.who = NOBODY
		return end_comyn()
	}
	if (lochaber && !badenoch) {
		go_home_to(game.who, AREA_LOCHABER)
		game.who = NOBODY
		return end_comyn()
	}
	if (!lochaber && !badenoch) {
		game.comyn_defected = true
		game.active = ENEMY[game.active]
		game.who = swap_blocks(game.who)
	} else {
		game.comyn_defected = false
	}
	game.state = 'comyn'
}

states.comyn = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for " + game.active + " to move Comyn to one of his home areas."
		view.prompt = "Nobles go Home: Move Comyn to one of his home areas."
		gen_action_area(view, AREA_BADENOCH)
		gen_action_area(view, AREA_LOCHABER)
	},
	area: function (to) {
		go_home_to(game.who, to, game.comyn_defected)
		game.who = NOBODY
		end_comyn()
	},
}

function end_comyn() {
	game.who = NOBODY
	game.active = game.going_home
	delete game.comyn_defected
	if (game.active === ENGLAND) {
		print_turn_log_no_count("English nobles went home:")
		scottish_nobles_go_home()
	} else {
		goto_moray()
	}
}

function goto_moray() {
	delete game.going_home
	delete game.bruce_home
	delete game.comyn_home

	if (is_on_map(B_MORAY) && game.location[B_MORAY] !== AREA_MORAY && is_friendly_or_neutral_area(AREA_MORAY)) {
		game.state = 'moray'
		game.active = SCOTLAND
		game.who = B_MORAY
	} else {
		goto_scottish_king()
	}
}

states.moray = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for Scotland to move Moray."
		view.prompt = "Nobles go Home: Move Moray to his home area or remain where he is."
		gen_action_area(view, game.location[B_MORAY])
		gen_action_area(view, AREA_MORAY)
	},
	disband: function () {
		game.turn_log.push([area_tag(AREA_MORAY), "Pool"])
		disband(B_MORAY)
		game.who = NOBODY
		goto_scottish_king()
	},
	area: function (to) {
		let from = game.location[B_MORAY]
		if (to !== from)
			game.turn_log.push([area_tag(AREA_MORAY), area_tag(to)])
		game.location[B_MORAY] = to
		game.who = NOBODY
		goto_scottish_king()
	},
}

function king_can_go_home(current) {
	for (let where = first_map_area; where < area_count; ++where)
		if (where !== current && is_cathedral_area(where))
			if (is_friendly_or_neutral_area(where))
				return true
	return false
}

function goto_scottish_king() {
	print_turn_log_no_count("Scottish nobles went home:")

	// We can end winter early if Moray and Wallace are dead or on the map, and Moray is not overstacked
	if (game.year === game.end_year) {
		let e = count_english_nobles()
		let s = count_scottish_nobles()
		// We have a clear winner.
		if (s > 7 || e > 7)
			return goto_game_over()
		// Moray is dead so there can be no tie.
		if (game.location[B_MORAY] === NOWHERE)
			return goto_game_over()
		// Wallace is dead so there can be no tie breaker.
		if (game.location[B_WALLACE] === NOWHERE)
			return goto_game_over()
		// A tie is possible, need to continue to disband and build phase...
	}

	if (is_on_map(B_KING) && king_can_go_home(game.location[B_KING])) {
		game.state = 'scottish_king'
		game.active = SCOTLAND
		game.who = B_KING
	} else {
		goto_edward_wintering()
	}
}

states.scottish_king = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for Scotland to move the King."
		view.prompt = "Scottish King: Move the King to a cathedral or remain where he is."
		gen_action_area(view, game.location[B_KING])
		for (let where = first_map_area; where < area_count; ++where) {
			if (is_cathedral_area(where))
				if (is_friendly_or_neutral_area(where))
					gen_action_area(view, where)
		}
	},
	disband: function () {
		log("Scottish King disbanded.")
		disband(B_KING)
		game.who = NOBODY
		goto_edward_wintering()
	},
	area: function (to) {
		if (game.location[B_KING] !== to) {
			log("Scottish King moved to " + area_tag(to) + ".")
			game.location[B_KING] = to
		}
		game.who = NOBODY
		goto_edward_wintering()
	},
}

function is_in_scotland(who) {
	return is_on_map(who) && game.location[who] !== AREA_ENGLAND
}

function goto_edward_wintering() {
	if (game.edward === 1 && game.year !== 1306 && is_in_scotland(B_EDWARD) && !game.wintered_last_year) {
		game.active = ENGLAND
		game.who = B_EDWARD
		game.state = 'edward_wintering'
		return
	}

	if (game.edward === 1 && game.year === 1306) {
		log("Edward I died.")
		game.edward = 2
	}

	if (is_on_map(B_EDWARD)) {
		log("Edward disbanded.")
		disband(B_EDWARD)
	}

	game.wintered_last_year = false
	goto_english_disbanding()
}

function disband_edward() {
	log("Edward disbanded.")
	disband(B_EDWARD)
	game.who = NOBODY
	game.wintered_last_year = false
	goto_english_disbanding()
}

function winter_edward() {
	log("Edward wintered in " + area_tag(game.location[B_EDWARD]) + ".")
	game.who = NOBODY
	game.wintered_last_year = true
	goto_english_disbanding()
}

states.edward_wintering = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for England to winter in Scotland or disband."
		view.prompt = "Edward Wintering: Winter in Scotland or disband."
		gen_action(view, 'winter')
		gen_action(view, 'disband')
		gen_action_area(view, game.location[B_EDWARD])
		gen_action_area(view, AREA_ENGLAND)
	},
	winter: function () {
		winter_edward()
	},
	disband: function () {
		disband_edward()
	},
	area: function (to) {
		if (to === AREA_ENGLAND)
			disband_edward()
		else
			winter_edward()
	},
}

function goto_english_disbanding() {
	game.active = ENGLAND
	game.turn_log = []
	let ask = false
	for (let b = 0; b < block_count; ++b) {
		let where = game.location[b]

		// All (English) blocks in England must disband.
		// Scottish blocks disband later during the castle limit check.
		if (where === AREA_ENGLAND && block_owner(b) === ENGLAND) {
			game.turn_log.push([area_tag(AREA_ENGLAND)])
			disband(b)
		}

		if (block_owner(b) === ENGLAND && is_on_map(b)) {
			// Knights, Archers, & Hobelars must disband except when wintering with Edward.
			let type = block_type(b)
			if (type === 'knights' || type === 'archers' || type === 'hobelars') {
				if (where === game.location[B_EDWARD]) {
					ask = true
				} else {
					game.turn_log.push([area_tag(where)])
					disband(b)
				}
			}

			// Infantry may remain in Scotland subject to Castle Limits or wintering with Edward.
			if (type === 'infantry') {
				ask = true
			}
		}
	}
	if (ask) {
		game.state = 'english_disbanding'
		clear_undo()
	} else {
		print_turn_log("disbanded")
		goto_wallace()
	}
}

states.english_disbanding = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for England to disband."

		gen_action_undo(view)

		// Mandatory disbanding
		let okay_to_end = true
		for (let b = 0; b < block_count; ++b) {
			if (block_owner(b) === ENGLAND && is_on_map(b)) {
				let where = game.location[b]
				let type = block_type(b)
				if (type === 'infantry') {
					if (!is_within_castle_limit(where) && where !== game.location[B_EDWARD]) {
						okay_to_end = false
						gen_action_block(view, b)
					}
				}
			}
		}

		if (!okay_to_end)
		{
			view.prompt = "English Disbanding: Disband units in excess of castle limits."
		}
		else
		{
			// Voluntary disbanding
			view.prompt = "English Disbanding: You may disband units to the pool."
			gen_action(view, 'end_disbanding')
			for (let b = 0; b < block_count; ++b) {
				if (block_owner(b) === ENGLAND && is_on_map(b)) {
					let type = block_type(b)
					if (type === 'knights' || type === 'archers' || type === 'hobelars')
						gen_action_block(view, b)
					if (type === 'infantry')
						gen_action_block(view, b)
				}
			}
		}
	},
	block: function (who) {
		push_undo()
		game.turn_log.push([area_tag(game.location[who])])
		disband(who)
	},
	end_disbanding: function () {
		print_turn_log("disbanded")
		clear_undo()
		goto_wallace()
	},
	undo: pop_undo
}

function heal_wallace() {
	let old = game.steps[B_WALLACE]
	game.steps[B_WALLACE] = Math.min(block_max_steps(B_WALLACE), game.steps[B_WALLACE] + 2)
	let n = game.steps[B_WALLACE] - old
	if (n === 1)
		log("Wallace gained 1 step.")
	else if (n === 2)
		log("Wallace gained 2 steps.")
}

function goto_wallace() {
	game.active = SCOTLAND
	if (game.location[B_WALLACE] === AREA_SELKIRK) {
		heal_wallace()
		goto_scottish_disbanding()
	} else if (is_on_map(B_WALLACE) && is_friendly_or_neutral_area(AREA_SELKIRK)) {
		game.state = 'wallace'
		game.who = B_WALLACE
	} else {
		goto_scottish_disbanding()
	}
}

states.wallace = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for Scotland to move Wallace."
		view.prompt = "Scottish Disbanding: Move Wallace to Selkirk and gain 2 steps or remain where he is."
		gen_action_area(view, game.location[B_WALLACE])
		gen_action_area(view, AREA_SELKIRK)
	},
	area: function (to) {
		if (to === AREA_SELKIRK) {
			log("Wallace went home to " + area_tag(to) + ".")
			heal_wallace()
		}
		game.location[B_WALLACE] = to
		game.who = NOBODY
		goto_scottish_disbanding()
	},
}

function goto_scottish_disbanding() {
	game.active = SCOTLAND
	game.turn_log = []
	let ask = false
	for (let b = 0; b < block_count; ++b) {
		if (block_owner(b) === SCOTLAND && is_on_map(b)) {
			let type = block_type(b)
			if (type !== 'nobles')
				ask = true
		}
	}
	if (ask) {
		game.state = 'scottish_disbanding'
		clear_undo()
	} else {
		print_turn_log("disbanded")
		goto_scottish_builds()
	}
}

states.scottish_disbanding = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for Scotland to disband."

		gen_action_undo(view)

		// Mandatory disbanding
		let okay_to_end = true
		for (let b = 0; b < block_count; ++b) {
			if (block_owner(b) === SCOTLAND && is_on_map(b)) {
				let where = game.location[b]
				if (b === B_WALLACE && where === AREA_SELKIRK)
					continue
				let type = block_type(b)
				if (type !== 'nobles') {
					if (!is_within_castle_limit(where)) {
						okay_to_end = false
						gen_action_block(view, b)
					}
				}
			}
		}

		if (!okay_to_end) {
			view.prompt = "Scottish Disbanding: Disband units in excess of castle limits."
		} else {
			// Voluntary disbanding
			view.prompt = "Scottish Disbanding: You may disband units to the pool."
			gen_action(view, 'end_disbanding')
			for (let b = 0; b < block_count; ++b) {
				if (block_owner(b) === SCOTLAND && is_on_map(b)) {
					let type = block_type(b)
					if (type !== 'nobles')
						gen_action_block(view, b)
				}
			}
		}
	},
	block: function (who) {
		push_undo()
		game.turn_log.push([area_tag(game.location[who])])
		disband(who)
	},
	end_disbanding: function () {
		print_turn_log("disbanded")
		clear_undo()
		goto_scottish_builds()
	},
	undo: pop_undo
}

function goto_scottish_builds() {
	game.active = SCOTLAND

	if (!game.french_knights && count_scottish_nobles() >= 8) {
		log("French knights added to pool.")
		game.french_knights = true
		game.location[B_FRENCH_KNIGHTS] = S_BAG
		game.steps[B_FRENCH_KNIGHTS] = block_max_steps(B_FRENCH_KNIGHTS)
	}

	game.rp = Array(area_count).fill(0)
	for (let where = first_map_area; where < area_count; ++where)
		if (is_friendly_area(where))
			game.rp[where] = castle_limit(where)
	game.state = 'scottish_builds'
	game.turn_log = []
	clear_undo()
}

function can_build_scottish_block_in(where) {
	if (is_under_castle_limit(where)) {
		if (where === AREA_LANARK || where === AREA_BADENOCH)
			return count_blocks_in_area_excluding(S_BAG, [ B_NORSE, B_FRENCH_KNIGHTS ]) > 0
		else
			return count_blocks_in_area(S_BAG) > 0
	}
	return false
}

states.scottish_builds = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for Scotland to build."
		gen_action_undo(view)
		let done = true
		for (let where = 1; where < area_count; ++where) {
			let rp = game.rp[where]
			if (rp > 0) {
				for (let b = 0; b < block_count; ++b) {
					if (game.location[b] === where && game.steps[b] < block_max_steps(b)) {
						gen_action_block(view, b)
						done = false
					}
				}
				if (can_build_scottish_block_in(where)) {
					gen_action_area(view, where)
					done = false
				}
			}
		}
		if (done) {
			view.prompt = "Scottish Builds: Deploy or reinforce armies \u2014 done."
			gen_action(view, 'end_builds')
		} else {
			view.prompt = "Scottish Builds: Deploy or reinforce armies."
		}
	},
	area: function (where) {
		let who
		if (where === AREA_LANARK || where === AREA_BADENOCH)
			who = draw_from_bag(S_BAG, [ B_NORSE, B_FRENCH_KNIGHTS ])
		else
			who = draw_from_bag(S_BAG)
		if (who !== NOBODY) {
			clear_undo() // no undo after drawing from the bag!
			game.turn_log.push([area_tag(where)])
			game.location[who] = where
			game.steps[who] = 1
			--game.rp[where]
		}
	},
	block: function (who) {
		push_undo()
		let where = game.location[who]
		game.turn_log.push([area_tag(where)])
		--game.rp[where]
		++game.steps[who]
	},
	end_builds: function () {
		print_turn_log("built")
		game.rp = null
		clear_undo()
		goto_english_builds()
	},
	undo: pop_undo
}

function goto_english_builds() {
	game.active = ENGLAND
	game.rp = Array(area_count).fill(0)
	for (let where = first_map_area; where < area_count; ++where)
		if (is_friendly_area(where))
			game.rp[where] = castle_limit(where)
	game.state = 'english_builds'
	game.turn_log = []
}

states.english_builds = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Waiting for England to build."
		gen_action_undo(view)
		let done = true
		for (let where = 1; where < area_count; ++where) {
			let rp = game.rp[where]
			if (rp > 0) {
				for (let b = 0; b < block_count; ++b) {
					if (game.location[b] === where && game.steps[b] < block_max_steps(b)) {
						let type = block_type(b)
						if (type === 'nobles' || type === 'infantry') {
							gen_action_block(view, b)
							done = false
						}
					}
				}
			}
		}
		if (done) {
			view.prompt = "English Builds: Reinforce armies \u2014 done."
			gen_action(view, 'end_builds')
		} else {
			view.prompt = "English Builds: Reinforce armies."
		}
	},
	block: function (who) {
		push_undo()
		let where = game.location[who]
		game.turn_log.push([area_tag(where)])
		--game.rp[where]
		++game.steps[who]
	},
	end_builds: function () {
		clear_undo()
		print_turn_log("built")
		game.rp = null
		goto_english_feudal_levy()
	},
	undo: pop_undo
}

function goto_english_feudal_levy() {
	if (!is_on_map(B_EDWARD)) {
		let count = Math.ceil(count_blocks_in_area(E_BAG) / 2)
		log("English feudal levy:\n" + count + " England")
		deploy_english(count)
	}
	end_winter_turn()
}

function end_winter_turn() {
	if (count_english_nobles() === 0) {
		game.victory = "Scotland won by controlling all the nobles!"
		game.result = SCOTLAND
	}
	if (count_scottish_nobles() === 0) {
		game.victory = "England won by controlling all the nobles!"
		game.result = ENGLAND
	}
	if (game.victory)
		return goto_game_over()

	if (++game.year > game.end_year)
		goto_game_over()
	else
		start_year()
}

function goto_game_over() {
	if (!game.victory) {
		let e = count_english_nobles()
		let s = count_scottish_nobles()
		if (e > s) {
			game.victory = "England won by controlling the most nobles!"
			game.result = ENGLAND
		} else if (s > e) {
			game.victory = "Scotland won by controlling the most nobles!"
			game.result = SCOTLAND
		} else {
			if (is_on_map(B_WALLACE)) {
				game.victory = "Tied for control of nobles. Scotland won because Wallace was on the map!"
				game.result = SCOTLAND
			} else {
				game.victory = "Tied for control of nobles. England won because Wallace was dead or in the draw pool!"
				game.result = ENGLAND
			}
		}
	}
	log("")
	log(game.victory)
	game.active = "None"
	game.state = 'game_over'
}

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

function make_battle_view() {
	let battle = {
		EF: [], ER: [],
		SF: [], SR: [],
		flash: game.flash
	}

	battle.title = get_attacker(game.where) + " attacks " + area_name(game.where)
	battle.title += " \u2014 round " + game.battle_round + " of 3"

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

	fill_cell(battle.ER, ENGLAND, b => is_battle_reserve(b))
	fill_cell(battle.EF, ENGLAND, b => !is_battle_reserve(b))
	fill_cell(battle.SR, SCOTLAND, b => is_battle_reserve(b))
	fill_cell(battle.SF, SCOTLAND, b => !is_battle_reserve(b))

	return battle
}

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

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

		attacker: [],
		border_limit: [],
		last_used: [],
		main_border: [],
		main_origin: [],

		show_cards: 0,
		who: NOBODY,
		where: NOWHERE,
	}

	if (options.rng)
		game.rng = options.rng

	log(".h1 " + scenario)

	if (scenario === "The Bruce")
		setup_the_bruce()
	else if (scenario === "Braveheart")
		setup_braveheart()
	else if (scenario === "Campaign")
		setup_campaign()
	else
		throw new Error("Unknown scenario:", scenario)

	if (options.autohit)
		game.autohit = 1

	if (options.immediate)
		game.immediate = 1

	if (options.schiltroms) {
		log("")
		log("Schiltroms:")
		logi("Scottish infantry fire at +1 in battles where the English have no archers.")
		log("")
		game.schiltroms = 1
	}

	start_year()
	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 + " in state " + game.state)
	}
	return game
}

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

exports.is_checkpoint = (a, b) => a.turn !== b.turn

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

	let view = {
		log: game.log,
		year: game.year,
		turn: 6 - (game.e_hand.length + (game.e_card ? 1 : 0)),
		edward: game.edward,
		e_vp: count_english_nobles(),
		s_vp: count_scottish_nobles(),
		e_card: (game.show_cards || current === ENGLAND) ? game.e_card : 0,
		s_card: (game.show_cards || current === SCOTLAND) ? game.s_card : 0,
		hand: (current === ENGLAND) ? game.e_hand : (current === SCOTLAND) ? game.s_hand : observer_hand(),
		who: (game.active === current) ? game.who : NOBODY,
		where: game.where,
		location: game.location,
		steps: game.steps,
		moved: game.moved,
		last_used: game.last_used,
		border_limit: game.border_limit,
		active: game.active,
	}

	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
}

// 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 set_toggle(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 array_insert(set, a, item)
}

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

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