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

// TODO: optional rule - force marches

// TODO: 6.2 - In Sieges, the attacker /may/ retreat or stay on siege.
// TODO: new combat deployment in round 2/3 if defenders are wiped out and reserves are coming?
//		see https://boardgamegeek.com/thread/423599/article/3731006
// TODO: sea move into attacked fortified port as defender responder? -- not besieged yet

exports.scenarios = [
	"Standard"
]

exports.roles = [
	"Franks",
	"Saracens",
]

const { CARDS, BLOCKS, TOWNS, PORTS, ROADS, SHIELDS, block_index, town_index } = require('./data')

const FRANKS = "Franks"
const SARACENS = "Saracens"
const OBSERVER = "Observer"
const BOTH = "Both"

const NOWHERE = 0
const DEAD = 1
const F_POOL = 2
const S_POOL = 3
const SEA = 4

const ENGLAND = 5
const FRANCE = 6
const GERMANIA = 7

const first_town = 5 // TODO: exclude staging areas? include sea?
const last_town = TOWNS.length - 1
const last_block = BLOCKS.length - 2 // assassins are not a real block

const ALEPPO = town_index["Aleppo"]
const ANTIOCH = town_index["Antioch"]
const DAMASCUS = town_index["Damascus"]
const MASYAF = town_index["Masyaf"]
const ST_SIMEON = town_index["St. Simeon"]
const TRIPOLI = town_index["Tripoli"]
const TYRE = town_index["Tyre"]

const NOBODY = -1
const ASSASSINS = block_index["Assassins"]
const RICHARD = block_index["Richard"]
const ROBERT = block_index["Robert"]
const CROSSBOWS = block_index["Crossbows"]
const SALADIN = block_index["Saladin"]
const AL_ADIL = block_index["Al Adil"]
const AL_AZIZ = block_index["Al Aziz"]
const AL_AFDAL = block_index["Al Afdal"]
const AL_ZAHIR = block_index["Al Zahir"]

const ENGLISH_CRUSADERS = [ RICHARD, ROBERT, CROSSBOWS ]
const GERMAN_CRUSADERS = [ "Barbarossa", "Frederik", "Leopold" ].map(name => block_index[name])
const FRENCH_CRUSADERS = [ "Philippe", "Hugues", "Fileps" ].map(name => block_index[name])
const SALADIN_FAMILY = [ SALADIN, AL_ADIL, AL_AZIZ, AL_AFDAL, AL_ZAHIR ]

const INTRIGUE = 3
const WINTER_CAMPAIGN = 6

const GERMAN_ROADS = [ ST_SIMEON, ANTIOCH, ALEPPO ]

const KINGDOMS = {
	Syria: SARACENS,
	Antioch: FRANKS,
	Tripoli: FRANKS,
	Jerusalem: FRANKS,
	Egypt: SARACENS,
}

const VICTORY_TOWNS = [
	town_index["Aleppo"],
	town_index["Damascus"],
	town_index["Egypt"],
	town_index["Antioch"],
	town_index["Tripoli"],
	town_index["Acre"],
	town_index["Jerusalem"]
]

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

const ATTACK_MARK = "*"
const RESERVE_MARK_1 = "\u2020"
const RESERVE_MARK_2 = "\u2021"

const block_seats = []
const block_seat_names = []
const block_seat_names_or = []

function list_seats(who) {
	if (block_type(who) === 'nomads')
		return [ block_home(who) ]
	let list = []
	for (let town = first_town; town <= last_town; ++town)
		if (set_has(SHIELDS[town], who))
			list.push(town)
	return list
}

for (let b = 0; b <= last_block; ++b) {
	block_seats[b] = list_seats(b)
	let names = block_seats[b].map(town_name)
	block_seat_names[b] = names.join(", ")
	block_seat_names_or[b] = join(names, "or")
}

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 active_adjective() {
	return (game.active === FRANKS ? "Frank" : "Saracen")
}

function join(list, conj = "or") {
	if (list.length === 0) return ""
	if (list.length === 1) return list[0]
	if (list.length === 2) return `${list[0]} ${conj} ${list[1]}`
	return `${list.slice(0,-1).join(", ")}, ${conj} ${list[list.length-1]}`
}

function log_move_start(from) {
	game.move_buf = [ from ]
}

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

function log_move_end() {
	if (game.move_buf && game.move_buf.length > 1)
		game.summary.push(game.move_buf)
	delete game.move_buf
}

function print_summary(text, skip_if_empty = false) {
	if (skip_if_empty && game.summary.length === 0) {
		delete game.summary
		return
	}

	let lines = game.summary.map(function (move) {
		let s = ""
		for (let i = 0; i < move.length; ++i) {
			let x = move[i]
			if (i > 0)
				s += " \u2192 "
			if (typeof x === 'number')
				s += "#" + x
			else
				s += x
		}
		return s
	}).sort()
	delete game.summary

	log(text)

	let last = lines[0]
	let n = 0
	for (let entry of lines) {
		if (entry !== last) {
			logi(n + " " + last)
			n = 0
		}
		++n
		last = entry
	}
	if (n > 0)
		logi(n + " " + last)
	else
		logi("nothing.")
}

const id_player = [ null, FRANKS, SARACENS ]

function player_id(p) {
	if (p === FRANKS) return 1
	if (p === SARACENS) return 2
	return 0
}

function enemy(p) {
	if (p === FRANKS) return SARACENS
	if (p === SARACENS) return FRANKS
	return null
}

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

function is_winter() {
	return game.turn === 6
}

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

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

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

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

function shuffle_deck() {
	let deck = []
	for (let c = 1; c <= 27; ++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 select_random_block(where) {
	let list = []
	for (let b = 0; b <= last_block; ++b)
		if (game.location[b] === where)
			list.push(b)
	if (list.length === 0)
		return NOBODY
	return list[random(list.length)]
}

function select_random_enemy_block(where) {
	let list = []
	for (let b = 0; b <= last_block; ++b)
		if (game.location[b] === where && block_owner(b) === enemy(game.active))
			list.push(b)
	if (list.length === 0)
		return NOBODY
	return list[random(list.length)]
}

function town_name(where) {
	return TOWNS[where].name
}

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

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

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

function is_home_seat(where, who) {
	if (block_type(who) === 'nomads')
		return where === block_home(who)
	if (set_has(SHIELDS[where], who))
		return true
	return false
}

function block_pool(who) {
	if (BLOCKS[who].owner === FRANKS)
		return F_POOL
	return S_POOL
}

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

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

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

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

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

function is_saladin_family(who) {
	return who === SALADIN || who === AL_ADIL || who === AL_AZIZ || who === AL_AFDAL || who === AL_ZAHIR
}

function is_english_crusader(who) {
	return who === RICHARD || who === ROBERT || who === CROSSBOWS
}

function are_crusaders_not_in_pool(crusaders) {
	for (let b of crusaders)
		if (game.location[b] === F_POOL)
			return false
	return true
}

function is_block_on_map(who) {
	let location = game.location[who]
	return location && location !== DEAD && location !== F_POOL && location !== S_POOL
}

function is_block_on_land(who) {
	let location = game.location[who]
	return location && location !== DEAD && location !== F_POOL && location !== S_POOL &&
		location !== ENGLAND && location !== FRANCE && location !== GERMANIA
}

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

function road_was_last_used_by_enemy(from, to) {
	return map_get(game.last_used, road_id(from, to)) === player_id(enemy(game.active))
}

function road_was_last_used_by_friendly(from, to) {
	return map_get(game.last_used, road_id(from, to)) === player_id(game.active)
}

function road_type(a, b) {
	return ROADS[road_id(a,b)]
}

function road_limit(a, b) {
	return map_get(game.road_limit, road_id(a,b), 0)
}

function set_road_limit(a, b, n) {
	map_set(game.road_limit, road_id(a,b), n)
}

function reset_road_limits() {
	game.road_limit.length = 0
}

function count_player(p, where) {
	let count = 0
	for (let b = 0; b <= last_block; ++b)
		if (game.location[b] === where && block_owner(b) === p)
			++count
	return count
}

function count_friendly(where) {
	let p = game.active
	let count = 0
	for (let b = 0; b <= last_block; ++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 <= last_block; ++b)
		if (game.location[b] === where && block_owner(b) === p)
			++count
	return count
}

function count_friendly_in_field(where) {
	let p = game.active
	let count = 0
	for (let b = 0; b <= last_block; ++b)
		if (game.location[b] === where && block_owner(b) === p)
			if (!is_block_in_castle(b))
				++count
	return count
}

function count_enemy_in_field(where) {
	let p = enemy(game.active)
	let count = 0
	for (let b = 0; b <= last_block; ++b)
		if (game.location[b] === where && block_owner(b) === p)
			if (!is_block_in_castle(b))
				++count
	return count
}

function count_friendly_in_field_excluding_reserves(where) {
	let p = game.active
	let count = 0
	for (let b = 0; b <= last_block; ++b)
		if (game.location[b] === where && block_owner(b) === p)
			if (!is_block_in_castle(b) && !is_reserve(b))
				++count
	return count
}

function count_enemy_in_field_excluding_reserves(where) {
	let p = enemy(game.active)
	let count = 0
	for (let b = 0; b <= last_block; ++b)
		if (game.location[b] === where && block_owner(b) === p)
			if (!is_block_in_castle(b) && !is_reserve(b))
				++count
	return count
}

function count_blocks_in_castle(where) {
	let n = 0
	for (let b = 0; b <= last_block; ++b)
		if (game.location[b] === where && set_has(game.castle, b))
			++n
	return n
}

function count_enemy_in_field_and_reserve(where) {
	let n = 0
	for (let b = 0; b <= last_block; ++b)
		if (block_owner(b) !== game.active)
			if (game.location[b] === where && !set_has(game.castle, b))
				++n
	return n
}

function count_reserves(where) {
	let n = 0
	for (let b = 0; b <= last_block; ++b)
		if (block_owner(b) === game.active)
			if (game.location[b] === where && is_reserve(b))
				++n
	return n
}

function is_player_kingdom(p, where) {
	return KINGDOMS[TOWNS[where].region] === p
}

function is_friendly_kingdom(where) {
	return KINGDOMS[TOWNS[where].region] === game.active
}

function is_enemy_kingdom(where) {
	return KINGDOMS[TOWNS[where].region] !== game.active
}

/* Town queries include castle and field. */
function is_friendly_town(where) {
	return (count_enemy(where) === 0) && (count_friendly(where) > 0 || is_friendly_kingdom(where))
}
function is_enemy_town(where) {
	return (count_friendly(where) === 0) && (count_enemy(where) > 0 || is_enemy_kingdom(where))
}
function is_vacant_town(where) {
	return count_friendly(where) === 0 && count_enemy(where) === 0
}
function is_contested_town(where) {
	return count_friendly(where) > 0 && count_enemy(where) > 0
}
function is_enemy_occupied_town(where) {
	return count_enemy(where) > 0
}

/* Field queries exclude castles. */
function is_friendly_field(where) {
	return (count_enemy_in_field(where) === 0) && (count_friendly_in_field(where) > 0 || is_friendly_kingdom(where))
}
function is_enemy_field(where) {
	return (count_friendly_in_field(where) === 0) && (count_enemy_in_field(where) > 0 || is_enemy_kingdom(where))
}
function is_contested_field(where) {
	return count_friendly_in_field(where) > 0 && count_enemy_in_field(where) > 0
}
function is_friendly_or_vacant_field(where) {
	return is_friendly_field(where) || is_vacant_town(where)
}
function is_enemy_or_contested_field(where) {
	return (count_enemy_in_field(where) > 0 || is_enemy_kingdom(where))
}

/* Battle field queries exclude castles and reserves. */
function is_contested_battle_field() {
	let f = count_friendly_in_field_excluding_reserves(game.where)
	let e = count_enemy_in_field_excluding_reserves(game.where)
	return f > 0 && e > 0
}
function is_friendly_battle_field() {
	return count_enemy_in_field_excluding_reserves(game.where) === 0
}
function is_enemy_battle_field() {
	return count_friendly_in_field_excluding_reserves(game.where) === 0
}

function is_reserve(who) {
	return set_has(game.reserves1, who) || set_has(game.reserves2, who)
}

function is_field_attacker(who) {
	if (game.location[who] === game.where && block_owner(who) === game.attacker[game.where])
		return !is_reserve(who) && !is_block_in_castle(who)
	return false
}

function is_field_defender(who) {
	if (game.location[who] === game.where && block_owner(who) !== game.attacker[game.where])
		return !is_reserve(who) && !is_block_in_castle(who)
	return false
}

function is_field_combatant(who) {
	if (game.location[who] === game.where)
		return !is_reserve(who) && !is_block_in_castle(who)
	return false
}

function is_block_in_field(who) {
	return !is_reserve(who) && !is_block_in_castle(who)
}

function is_siege_attacker(who) {
	return set_has(game.storming, who)
}

function is_siege_defender(who) {
	return is_block_in_castle_in(who, game.where)
}

function is_siege_combatant(who) {
	return set_has(game.storming, who) || is_block_in_castle_in(who, game.where)
}

function castle_limit(where) {
	return TOWNS[where].rating
}

function is_more_room_in_castle(where) {
	return count_blocks_in_castle(where) < castle_limit(where)
}

function is_within_castle_limit(where) {
	return count_friendly(where) <= Math.max(1, castle_limit(where))
}

function is_castle_town(where) {
	return castle_limit(where) > 0
}

function is_under_siege(where) {
	return count_blocks_in_castle(where) > 0
}

function is_block_in_castle(b) {
	return set_has(game.castle, b)
}

function is_block_in_castle_in(b, town) {
	return game.location[b] === town && set_has(game.castle, b)
}

function besieged_player(where) {
	for (let b = 0; b <= last_block; ++b)
		if (is_block_in_castle_in(b, where))
			return block_owner(b)
	return null
}

function besieging_player(where) {
	return enemy(besieged_player(where))
}

function is_port(where) {
	return TOWNS[where].port
}

function is_friendly_port(where) {
	return TOWNS[where].port && is_friendly_field(where)
}

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

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

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

function count_pinned(where) {
	let count = 0
	for (let b = 0; b <= last_block; ++b)
		if (game.location[b] === where && block_owner(b) === game.active)
			if (!is_reserve(b))
				++count
	return count
}

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

function can_block_use_road(from, to) {
	if (game.active === game.guide) {
		switch (road_type(from, to)) {
		case 'iron-bridge':
			// https://boardgamegeek.com/thread/744750/20-rules-iron-bridge-question
			// fallthrough
		case 'major':
			return road_limit(from, to) < 8
		case 'minor':
			return road_limit(from, to) < 4
		}
	} else {
		switch (road_type(from, to)) {
		case 'iron-bridge':
			if (game.iron_bridge)
				return road_limit(from, to) < 3
			else
				return road_limit(from, to) < 4
		case 'major':
			return road_limit(from, to) < 4
		case 'minor':
			return road_limit(from, to) < 2
		}
	}
	return false
}

function can_block_land_move_to(who, from, to) {
	if (can_block_use_road(from, to)) {
		if (count_pinning(from) > 0)
			if (road_was_last_used_by_enemy(from, to))
				return false

		// cannot start or reinforce battles in winter
		if (is_winter() && is_enemy_occupied_town(to)) {
			// but can move through friendly sieges
			if (!is_friendly_field(to))
				return false
			if (game.distance + 1 >= block_move(who))
				return false
		}

		return true
	}
	return false
}

function can_germans_move(who) {
	let from = game.location[who]
	if (from === GERMANIA) {
		if (can_activate(who)) {
			for (let to of GERMAN_ROADS)
				if (can_germans_move_to(who, to))
					return true
		}
	}
	return false
}

function can_germans_move_to(who, to) {
	if (are_crusaders_not_in_pool(GERMAN_CRUSADERS)) {
		if (is_winter() && is_enemy_occupied_town(to))
			return false
		if (to === ALEPPO)
			return true
		if (to === ANTIOCH)
			return true
		if (to === ST_SIMEON)
			return road_limit(GERMANIA, ST_SIMEON) < 2
	}
	return false
}

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

function can_use_richards_sea_legs(who, to) {
	// English Crusaders may attack by sea.
	// If combined with another attack, the English must be the Main Attacker.
	if (is_english_crusader(who)) {
		if (is_enemy_or_contested_field(to)) {
			if (!game.attacker[to])
				return true
			if (game.attacker[to] === FRANKS)
				return (get_main_road(to) === ENGLAND)
		}
	}
	return false
}

function can_enter_besieged_port(where) {
	// Tripoli and Tyre are friendly to besieged defender!
	if (where === TRIPOLI || where === TYRE)
		if (besieged_player(where) === game.active)
			return count_blocks_in_castle(where) < castle_limit(where)
	return false
}

function can_leave_besieged_port(where) {
	// Tripoli and Tyre are friendly to besieged defender!
	if (where === TRIPOLI || where === TYRE)
		if (besieged_player(where) === game.active)
			return true
	return false
}

function can_block_sea_move_to(who, to) {
	if (is_port(to)) {
		// cannot start or reinforce battles in winter
		if (!is_winter()) {
			if (can_use_richards_sea_legs(who, to))
				return true
			if (can_enter_besieged_port(to))
				return true
		}
		return is_friendly_port(to)
	}
	return false
}

function can_block_sea_move_from(who, from) {
	if (from === TYRE || from === TRIPOLI) {
		// besieged player controls port!
		if (is_under_siege(from) && besieged_player(from) !== game.active)
			return false
	}
	if (is_friendly_port(from))
		return true
	if (can_leave_besieged_port(from))
		return true
	if (from === ENGLAND)
		return are_crusaders_not_in_pool(ENGLISH_CRUSADERS)
	if (from === FRANCE)
		return are_crusaders_not_in_pool(FRENCH_CRUSADERS)
	return false
}

function can_block_sea_move(who) {
	if (can_activate_for_sea_move(who)) {
		let from = game.location[who]
		if (can_block_sea_move_from(who, from)) {
			for (let to of PORTS)
				if (to !== from && can_block_sea_move_to(who, to))
					return true
		}
	}
	return false
}

function can_block_continue(who, from, to) {
	if (is_contested_field(to))
		return false
	if (game.distance >= block_move(who))
		return false
	return true
}

function can_block_retreat_to(who, to) {
	let from = game.location[who]
	if (block_owner(who) === game.attacker[from]) {
		if (!road_was_last_used_by_friendly(from, to))
			return false
	}
	if (is_friendly_field(to) || is_vacant_town(to)) {
		if (can_block_use_road(from, to)) {
			if (road_was_last_used_by_enemy(from, to))
				return false
			return true
		}
	}
	return false
}

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

function can_block_regroup_to(who, to) {
	// regroup during winter campaign
	if (is_winter() && is_enemy_occupied_town(to))
		return false
	if (is_friendly_field(to) || is_vacant_town(to)) {
		let from = game.location[who]
		if (can_block_use_road(from, to))
			return true
	}
	return false
}

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

function can_block_use_road_to_muster(from, to) {
	return can_block_use_road(from, to) && is_friendly_or_vacant_field(to)
}

function can_block_muster_with_3_moves(n0, muster) {
	for (let n1 of TOWNS[n0].exits) {
		if (can_block_use_road_to_muster(n0, n1)) {
			if (n1 === muster)
				return true
			for (let n2 of TOWNS[n1].exits) {
				if (n2 === n0) continue // don't backtrack!
				if (can_block_use_road_to_muster(n1, n2)) {
					if (n2 === muster)
						return true
					if (set_has(TOWNS[n2].exits, muster))
						if (can_block_use_road_to_muster(n2, muster))
							return true
				}
			}
		}
	}
	return false
}

function can_block_muster_with_2_moves(n0, muster, avoid) {
	for (let n1 of TOWNS[n0].exits) {
		if (n1 === avoid)
			continue
		if (can_block_use_road_to_muster(n0, n1)) {
			if (n1 === muster)
				return true
			if (set_has(TOWNS[n1].exits, muster))
				if (can_block_use_road_to_muster(n1, muster))
					return true
		}
	}
	return false
}

function can_block_muster_with_1_move(n0, muster) {
	if (set_has(TOWNS[n0].exits, muster))
		return can_block_use_road_to_muster(n0, muster)
	return false
}

function can_block_muster(who, muster) {
	let from = game.location[who]
	if (from === muster)
		return false
	if (can_activate(who)) {
		if (is_pinned(who, from))
			return false
		if (block_move(who) === 3)
			return can_block_muster_with_3_moves(from, muster)
		else
			return can_block_muster_with_2_moves(from, muster, NOWHERE)
	}
	return false
}

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

function can_muster_anywhere() {
	for (let where = first_town; where <= last_town; ++where)
		if (is_friendly_field(where))
			if (can_muster_to(where))
				return true
	return false
}

function lift_siege(where) {
	if (is_under_siege(where) && !is_contested_town(where)) {
		log("Siege lifted at #" + where + ".")
		for (let b = 0; b <= last_block; ++b)
			if (is_block_in_castle_in(b, where))
				set_delete(game.castle, b)
	}
}

function lift_all_sieges() {
	for (let town = first_town; town <= last_town; ++town)
		lift_siege(town)
}

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

function deploy(who, where) {
	game.location[who] = where
	game.steps[who] = block_max_steps(who)
}

function disband(who) {
	game.summary.push([game.location[who]])
	if (is_saladin_family(who) || block_type(who) === 'crusaders' || block_type(who) === 'military_orders')
		game.location[who] = NOWHERE // permanently eliminated
	else
		game.location[who] = DEAD // into to the pool next year
	game.steps[who] = block_max_steps(who)
}

function eliminate_block(who) {
	set_delete(game.castle, who)
	if (game.sallying) set_delete(game.sallying, who)
	if (game.storming) set_delete(game.storming, who)
	log(block_name(who) + " was eliminated.")
	if (is_saladin_family(who) || block_type(who) === 'crusaders' || block_type(who) === 'military_orders')
		game.location[who] = NOWHERE // permanently eliminated
	else
		game.location[who] = DEAD // into to the pool next year
	game.steps[who] = block_max_steps(who)
}

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

// DEPLOYMENT

function is_valid_frank_deployment() {
	let errors = []
	for (let town = first_town; town <= last_town; ++town)
		if (!is_within_castle_limit(town))
			errors.push(TOWNS[town].name)
	return errors
}

function goto_frank_deployment() {
	game.active = FRANKS
	game.state = 'frank_deployment'
}

states.frank_deployment = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Deployment: Waiting for " + game.active + "."
		gen_action_undo(view)
		let errors = is_valid_frank_deployment()
		if (errors.length === 0)
			gen_action(view, 'next')
		for (let b = 0; b <= last_block; ++b) {
			if (block_owner(b) === game.active && is_block_on_land(b))
				if (block_seats[b].length > 1)
					gen_action(view, 'block', b)
		}
		if (errors.length > 0)
			view.prompt = "Deployment: Too many blocks in " + join(errors, "and") + "."
		else
			view.prompt = "Deployment: You may make seat adjustments."
	},
	block: function (who) {
		push_undo()
		game.who = who
		game.state = 'frank_deployment_to'
	},
	next: function () {
		clear_undo()
		goto_saracen_deployment()
	},
	undo: pop_undo
}

states.frank_deployment_to = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Deployment: Waiting for " + game.active + "."
		view.prompt = "Deployment: Move " + block_name(game.who) + " to " + block_seat_names_or[game.who] + "."
		gen_action_undo(view)
		gen_action(view, 'block', game.who)
		let from = game.location[game.who]
		for (let town of block_seats[game.who])
			if (town !== from)
				gen_action(view, 'town', town)
	},
	town: function (where) {
		game.location[game.who] = where
		game.who = NOBODY
		game.state = 'frank_deployment'
	},
	block: pop_undo,
	undo: pop_undo
}

function goto_saracen_deployment() {
	for (let i = 0; i < 4; ++i) {
		let nomad = select_random_block(S_POOL)
		log(BLOCKS[nomad].name + " arrived in #" + block_home(nomad) + ".")
		deploy(nomad, block_home(nomad))
	}
	game.active = SARACENS
	game.state = 'saracen_deployment'
	game.who = SALADIN
}

states.saracen_deployment = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Deployment: Waiting for " + game.active + "."
		view.prompt = "Deployment: You may swap places with Saladin and any other block of his family."
		gen_action(view, 'next')
		gen_action_undo(view)
		if (game.location[SALADIN] === DAMASCUS) {
			for (let b of SALADIN_FAMILY)
				if (b !== SALADIN && game.location[b] !== game.location[SALADIN])
					gen_action(view, 'block', b)
		}
	},
	block: function (who) {
		push_undo()
		let saladin = game.location[SALADIN]
		game.location[SALADIN] = game.location[who]
		game.location[who] = saladin
		game.who = NOBODY
	},
	next: function () {
		clear_undo()
		game.who = NOBODY
		start_year()
	},
	undo: pop_undo
}

// GAME TURN

function is_friendly_town_for_player(p, where) {
	return (count_player(enemy(p), where) === 0) && (count_player(p, where) > 0 || is_player_kingdom(p, where))
}

function is_friendly_town_for_vp(p, town) {
	if (is_friendly_town_for_player(p, town))
		return true
	if (is_under_siege(town))
		return besieged_player(town) === p
	return false
}

function count_victory_points(p) {
	let vp = 0
	for (let town of VICTORY_TOWNS)
		if (is_friendly_town_for_vp(p, town))
			++ vp
	return vp
}

function check_sudden_death() {
	if (count_victory_points(FRANKS) === 7) {
		game.state = 'game_over'
		game.result = FRANKS
		game.victory = "Franks controlled all seven victory cities."
		log("")
		log(game.victory)
		return true
	}
	if (count_victory_points(SARACENS) === 7) {
		game.state = 'game_over'
		game.result = SARACENS
		game.victory = "Saracens controlled all seven victory cities."
		log("")
		log(game.victory)
		return true
	}
}

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

	game.turn = 1

	let deck = shuffle_deck()
	game.f_hand = deal_cards(deck, 6)
	game.s_hand = deal_cards(deck, 6)
	game.prior_f_card = 0
	game.prior_s_card = 0

	start_game_turn()
}

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

	game.guide = null
	game.jihad = null

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

	goto_card_phase()
}

// CARD PHASE

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

function resume_play_card() {
	if (game.s_card && game.f_card)
		reveal_cards()
	else if (game.f_card)
		game.active = SARACENS
	else if (game.s_card)
		game.active = FRANKS
	else
		game.active = BOTH
}

states.play_card = {
	prompt: function (view, current) {
		if (current === OBSERVER) {
			view.prior_s_card = game.prior_s_card
			view.prior_f_card = game.prior_f_card
			return view.prompt = "Card Phase: Waiting for players to play a card."
		}
		if (current === FRANKS) {
			view.prior_s_card = game.prior_s_card
			if (game.f_card) {
				view.prompt = "Card Phase: Waiting for Saracens to play a card."
			} else {
				view.prior_f_card = game.prior_f_card
				view.prompt = "Card Phase: Play a card."
				for (let c of game.f_hand)
					if (game.turn > 1 || c !== INTRIGUE)
						gen_action(view, 'play', c)
			}
		}
		if (current === SARACENS) {
			view.prior_f_card = game.prior_f_card
			if (game.s_card) {
				view.prompt = "Card Phase: Waiting for Franks to play a card."
			} else {
				view.prior_s_card = game.prior_s_card
				view.prompt = "Card Phase: Play a card."
				for (let c of game.s_hand)
					if (game.turn > 1 || c !== INTRIGUE)
						gen_action(view, 'play', c)
			}
		}
	},
	play: function (card, current) {
		if (current === FRANKS) {
			remove_from_array(game.f_hand, card)
			game.f_card = card
		}
		if (current === SARACENS) {
			remove_from_array(game.s_hand, card)
			game.s_card = card
		}
		resume_play_card()
	},
	undo: function (_, current) {
		if (current === FRANKS) {
			game.f_hand.push(game.f_card)
			game.f_card = 0
		}
		if (current === SARACENS) {
			game.s_hand.push(game.s_card)
			game.s_card = 0
		}
		resume_play_card()
	}
}

function reveal_cards() {
	log("")
	log("Franks played " + CARDS[game.f_card].name + ".")
	log("Saracens played " + CARDS[game.s_card].name + ".")
	game.show_cards = true

	if (CARDS[game.f_card].event && CARDS[game.s_card].event) {
		log("Game Turn cancelled.")
		game.prior_f_card = game.f_card
		game.prior_s_card = game.s_card
		end_game_turn()
		return
	}

	if (game.f_card === INTRIGUE) {
		game.f_card = game.prior_s_card
		log("Intrigue copied " + CARDS[game.f_card].name + ".")
	}
	if (game.s_card === INTRIGUE) {
		game.s_card = game.prior_f_card
		log("Intrigue copied " + CARDS[game.s_card].name + ".")
	}

	delete game.winter_campaign
	if (is_winter()) {
		if (game.f_card === WINTER_CAMPAIGN)
			game.winter_campaign = FRANKS
		if (game.s_card === WINTER_CAMPAIGN)
			game.winter_campaign = SARACENS
	}

	game.prior_f_card = game.f_card
	game.prior_s_card = game.s_card

	let fp = CARDS[game.f_card].event ? 10 : CARDS[game.f_card].moves
	let sp = CARDS[game.s_card].event ? 10 : CARDS[game.s_card].moves

	if (fp === sp) {
		let die = roll_d6()
		log("Random first player.")
		if (die > 3)
			++fp
		else
			++sp
	}

	if (fp > sp) {
		game.p1 = FRANKS
		game.p2 = SARACENS
	} else {
		game.p1 = SARACENS
		game.p2 = FRANKS
	}

	game.active = game.p1
	start_player_turn()
}

function start_player_turn() {
	log("")
	log(".h2 " + game.active)
	reset_road_limits()
	game.main_road = []
	let card = CARDS[game.active === FRANKS ? game.f_card : game.s_card]
	if (card.event)
		goto_event_card(card.event)
	else
		goto_move_phase(card.moves)
}

function end_player_turn() {
	game.moves = 0
	game.main_road = null

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

// EVENTS

function goto_event_card(event) {
	switch (event) {
	case 'assassins': goto_assassins(); break
	case 'guide': goto_guide(); break
	case 'jihad': goto_jihad(); break
	case 'manna': goto_manna(); break
	}
}

function goto_assassins() {
	game.state = 'assassins'
	game.who = ASSASSINS
	game.assassins = 1
}

states.assassins = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Assassins: Waiting for " + game.active + "."
		view.prompt = "Assassins: Choose one enemy block."
		for (let b = 0; b <= last_block; ++b) {
			if (is_block_on_land(b) && block_owner(b) === enemy(game.active))
				gen_action(view, 'block', b)
		}
	},
	block: function (who) {
		game.where = game.location[who]
		game.who = select_random_enemy_block(game.where)
		game.location[ASSASSINS] = game.where
		game.state = 'assassins_show_1'
	},
}

states.assassins_show_1 = {
	prompt: function (view, current) {
		view.assassinate = game.who
		view.who = ASSASSINS
		if (is_inactive_player(current))
			return view.prompt = "Assassins: Waiting for " + game.active + "."
		view.prompt = "Assassins: The assassins target " + block_name(game.who) + " in " + town_name(game.where) + "."
		gen_action(view, 'next')
		gen_action(view, 'block', game.who)
		gen_action(view, 'block', ASSASSINS)
	},
	next: assassins_next_1,
	block: assassins_next_1,
}

function assassins_next_1() {
	assassinate(game.who, game.where)
	game.state = 'assassins_show_2'
}

states.assassins_show_2 = {
	prompt: function (view, current) {
		view.assassinate = game.who
		view.who = ASSASSINS
		if (is_inactive_player(current))
			return view.prompt = "Assassins: Waiting for " + game.active + "."
		view.prompt = "Assassins: The assassins hit " + block_name(game.who) + " in " + town_name(game.where) + "."
		gen_action(view, 'next')
		gen_action(view, 'block', ASSASSINS)
		gen_action(view, 'town', MASYAF)
	},
	next: assassins_next_2,
	block: assassins_next_2,
	town: assassins_next_2,
}

function assassins_next_2() {
	game.location[ASSASSINS] = MASYAF
	game.who = NOBODY
	if (count_friendly(game.where) > 0 && count_enemy(game.where) === 0) {
		goto_regroup()
	} else {
		delete game.assassins
		game.where = NOWHERE
		end_player_turn()
	}
}

function assassinate(who, where) {
	let hits = 0
	let rolls = []
	for (let i = 0; i < 3; ++i) {
		let die = roll_d6()
		if (die <= 3) {
			rolls.push(DIE_HIT[die])
			++hits
		} else {
			rolls.push(DIE_MISS[die])
		}
	}
	hits = Math.min(hits, game.steps[who])
	log("Assassins hit " + block_name(who) + " at #" + where + ": " + rolls.join("") + ".")
	for (let i = 0; i < hits; ++i)
		reduce_block(who)
}

function goto_guide() {
	game.guide = game.active
	game.state = 'move_phase_event'
	game.summary = []
}

function goto_jihad() {
	game.jihad = game.active
	game.state = 'move_phase_event'
	game.summary = []
}

function goto_select_jihad() {
	game.jihad_list = []
	for (let where = first_town; where <= last_town; ++where)
		if (is_contested_field(where) || besieging_player(where) === game.active)
			game.jihad_list.push(where)
	if (game.jihad_list.length === 0) {
		delete game.jihad_list
		return end_player_turn()
	}
	if (game.jihad_list.length === 1) {
		game.jihad = game.jihad_list[0]
		log("Jihad in #" + game.jihad + ".")
		delete game.jihad_list
		return end_player_turn()
	}
	game.state = 'select_jihad'
}

states.select_jihad = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Jihad: Waiting for " + game.active + "."
		view.prompt = "Jihad: Select battle for Jihad."
		for (let town of game.jihad_list)
			gen_action(view, 'town', town)
	},
	town: function (where) {
		game.jihad = where
		log("Jihad in #" + game.jihad + ".")
		delete game.jihad_list
		end_player_turn()
	},
}

function goto_manna() {
	game.state = 'manna'
	game.moves = 3
	set_clear(game.moved)
	game.summary = []
}

states.manna = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Manna: Waiting for " + game.active + "."
		view.prompt = "Manna: Add one step to three different friendly blocks \u2014 " + game.moves + " left."
		gen_action_undo(view)
		gen_action(view, 'next')
		if (game.moves > 0) {
			for (let b = 0; b <= last_block; ++b) {
				if (is_block_on_land(b) && block_owner(b) === game.active && !set_has(game.moved, b))
					if (game.steps[b] < block_max_steps(b))
						gen_action(view, 'block', b)
			}
		}
	},
	block: function (who) {
		push_undo()
		game.summary.push([game.location[who]])
		++game.steps[who]
		--game.moves
		set_add(game.moved, who)
	},
	next: function () {
		clear_undo()
		print_summary(game.active + " used Manna:")
		set_clear(game.moved)
		end_player_turn()
	},
	undo: pop_undo
}

// MOVE PHASE

function queue_attack(who, round) {
	if (round === 1)
		return ATTACK_MARK
	if (round === 2) {
		set_add(game.reserves1, who)
		return RESERVE_MARK_1
	}
	if (round === 3) {
		set_add(game.reserves2, who)
		return RESERVE_MARK_2
	}
}

function get_main_road(to) {
	return map_get(game.main_road, to, NOWHERE)
}

function set_main_road(to, x) {
	map_set(game.main_road, to, x)
}

function move_block(who, from, to) {
	game.location[who] = to
	set_road_limit(from, to, road_limit(from, to) + 1)
	game.distance ++
	if (is_contested_field(to)) {
		map_set(game.last_used, road_id(from, to), player_id(game.active))

		// 6.56 Main Attack relief force by Player 2 arrives one round later than normal
		let relief_delay = 0
		if (game.active === game.p2 && besieged_player(to) === game.p2) {
			relief_delay = 1
		}

		if (!game.attacker[to]) {
			game.attacker[to] = game.active
			set_main_road(to, from)
			return queue_attack(who, 1 + relief_delay)
		} else {
			// Attacker main attack or reinforcements
			if (game.attacker[to] === game.active) {
				if (get_main_road(to) !== from)
					return queue_attack(who, 2 + relief_delay)
				return queue_attack(who, 1 + relief_delay)
			}

			// Defender reinforcements
			if (!get_main_road(to))
				set_main_road(to, from)

			if (get_main_road(to) === from) {
				return queue_attack(who, 2)
			} else {
				return queue_attack(who, 3)
			}
		}
	}
	return false
}

function goto_move_phase(moves) {
	game.state = 'move_phase'
	game.moves = moves
}

function end_move_phase() {
	if (game.moves > 0) {
		push_undo()
		game.state = 'confirm_end_move_phase'
		return
	}

	clear_undo()
	game.who = NOBODY
	game.where = NOWHERE
	game.moves = 0

	// declined to use winter campaign
	if (game.winter_campaign === game.active)
		delete game.winter_campaign

	if (game.active === game.jihad)
		goto_select_jihad()
	else
		end_player_turn()
}

states.confirm_end_move_phase = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Move Phase: Waiting for " + game.active + "."
		if (game.moves > 1)
			view.prompt = "Move Phase: You have " + game.moves + " moves left"
		else
			view.prompt = "Move Phase: You have 1 move left"
		view.prompt += " \u2014 are you sure you want to end the move phase?"
		gen_action_undo(view)
		gen_action(view, 'end_move_phase')
	},
	end_move_phase: function () {
		if (game.moves === 1)
			log(game.active + " did nothing with " + game.moves + " move.")
		else
			log(game.active + " did nothing with " + game.moves + " moves.")
		game.moves = 0
		end_move_phase()
	},
	undo: pop_undo
}

states.move_phase = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Move Phase: Waiting for " + game.active + "."
		if (game.moves === 0)
			view.prompt = "Move Phase: No moves left."
		else if (game.moves === 1)
			view.prompt = "Move Phase: 1 move left."
		else
			view.prompt = "Move Phase: " + game.moves + " moves left."
		gen_action_undo(view)
		gen_action(view, 'end_move_phase')
		if (game.moves > 0) {
			for (let b = 0; b <= last_block; ++b) {
				if (can_block_land_move(b))
					gen_action(view, 'block', b)
				if (can_block_sea_move(b))
					gen_action(view, 'block', b)
				if (can_germans_move(b))
					gen_action(view, 'block', b)
			}
			if (can_muster_anywhere())
				gen_action(view, 'muster')
			if (game.winter_campaign === game.active)
				gen_action(view, 'winter_campaign')
		}
	},
	winter_campaign: function () {
		push_undo()
		--game.moves
		game.state = 'winter_campaign'
	},
	muster: function () {
		push_undo()
		--game.moves
		game.state = 'muster'
	},
	block: function (who) {
		push_undo()
		game.summary = []
		game.who = who
		game.where = game.location[who]
		if (game.where === GERMANIA) {
			game.state = 'german_move_to'
		} else if (game.where === FRANCE || game.where === ENGLAND) {
			game.state = 'sea_move_to'
		} else {
			game.state = 'move_phase_to'
		}
	},
	end_move_phase: end_move_phase,
	undo: pop_undo
}

states.move_phase_event = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = group_move_name(1) + "Waiting for " + game.active + "."
		view.prompt = group_move_name(0) + "Choose a block to group move."
		gen_action_undo(view)
		gen_action(view, 'end_move_phase')
		// TODO: can_germans_move!
		for (let b = 0; b <= last_block; ++b)
			if (can_block_land_move(b))
				gen_action(view, 'block', b)
	},
	block: function (who) {
		push_undo()
		game.where = game.location[who]
		game.who = who
		game.distance = 0
		game.last_from = NOWHERE
		game.state = 'group_move_to'
	},
	end_move_phase: end_move_phase,
	undo: pop_undo
}

// Start new group move or sea move.
states.move_phase_to = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Move Phase: Waiting for " + game.active + "."
		view.prompt = "Move Phase: Move " + block_name(game.who)
		gen_action_undo(view)
		gen_action(view, 'block', game.who)
		let from = game.location[game.who]
		let can_group_move = false
		let can_sea_move = false
		if (can_block_land_move(game.who)) {
			for (let to of TOWNS[from].exits) {
				if (can_block_land_move_to(game.who, from, to)) {
					gen_action(view, 'town', to)
					can_group_move = true
				}
			}
		}
		if (can_block_sea_move(game.who)) {
			gen_action(view, 'town', SEA)
			can_sea_move = true
		}
		if (can_group_move && can_sea_move)
			view.prompt += " by road or by sea."
		else if (can_sea_move)
			view.prompt += " by sea."
		else
			view.prompt += " by road."
	},
	town: function (to) {
		set_add(game.moved, game.who)
		let from = game.location[game.who]
		if (to === SEA) {
			log_move_start(from)
			log_move_continue(to)
			game.location[game.who] = SEA
			game.state = 'sea_move_to'
			return
		}
		-- game.moves
		game.distance = 0
		log_move_start(from)
		let mark = move_block(game.who, from, to)
		if (mark)
			log_move_continue(to, mark)
		else
			log_move_continue(to)
		lift_siege(from)
		game.last_from = from
		if (!can_block_continue(game.who, from, to))
			end_move()
		else {
			game.state = 'group_move_to'
		}
	},
	block: pop_undo,
	undo: pop_undo
}

// GROUP MOVE

function group_move_name() {
	if (game.active === game.jihad) return "Jihad: "
	if (game.active === game.guide) return "Guide: "
	return "Group Move: "
}

function can_group_move_more() {
	for (let b = 0; b <= last_block; ++b)
		if (game.location[b] === game.where)
			if (can_block_land_move(b))
				return true
	return false
}

states.group_move_who = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = group_move_name(1) + "Waiting for " + game.active + "."
		view.prompt = group_move_name(0) + "Move blocks from " + town_name(game.where) + "."
		gen_action_undo(view)
		if (game.active === game.guide || game.active === game.jihad)
			gen_action(view, 'end_move_phase')
		else
			gen_action(view, 'end_group_move')
		for (let b = 0; b <= last_block; ++b)
			if (game.location[b] === game.where)
				if (can_block_land_move(b))
					gen_action(view, 'block', b)
	},
	block: function (who) {
		push_undo()
		game.who = who
		game.distance = 0
		game.last_from = NOWHERE
		game.state = 'group_move_to'
	},
	end_move_phase: function () {
		end_group_move()
		end_move_phase()
	},
	end_group_move: end_group_move,
	undo: pop_undo
}

states.group_move_to = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = group_move_name(1) + "Waiting for " + game.active + "."
		view.prompt = group_move_name(0) + "Move " + block_name(game.who) + "."
		gen_action_undo(view)
		if (game.distance === 0)
			gen_action(view, 'block', game.who)
		let from = game.location[game.who]
		if (game.distance > 0) {
			// cannot start or reinforce battles in winter
			if (!(is_winter() && is_enemy_occupied_town(from)))
				gen_action(view, 'town', from)
		}
		for (let to of TOWNS[from].exits) {
			if (to !== game.last_from && can_block_land_move_to(game.who, from, to)) {
				gen_action(view, 'town', to)
			}
		}
	},
	town: function (to) {
		set_add(game.moved, game.who)
		let from = game.location[game.who]
		if (to === from) {
			end_move()
			return
		}
		if (game.distance === 0)
			log_move_start(from)
		let mark = move_block(game.who, from, to)
		if (mark)
			log_move_continue(to, mark)
		else
			log_move_continue(to)
		lift_siege(from)
		game.last_from = from
		if (!can_block_continue(game.who, from, to))
			end_move()
	},
	block: pop_undo,
	undo: pop_undo
}

function end_move() {
	log_move_end()
	game.who = NOBODY
	game.distance = 0
	if (can_group_move_more())
		game.state = 'group_move_who'
	else
		end_group_move()
}

function end_group_move() {
	print_summary(game.active + " activated #" + game.where + ":")
	game.state = 'move_phase'
}

// SEA MOVE

states.german_move_to = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Move Phase: Waiting for " + game.active + "."
		view.prompt = "Move Phase: Move " + block_name(game.who) + " to Aleppo, Antioch, or St. Simeon."
		gen_action_undo(view)
		gen_action(view, 'block', game.who)
		for (let to of GERMAN_ROADS)
			if (can_germans_move_to(game.who, to))
				gen_action(view, 'town', to)
	},
	town: function (to) {
		--game.moves
		let from = GERMANIA
		game.location[game.who] = to
		set_add(game.moved, game.who)
		game.distance = 0
		let mark = move_block(game.who, from, to)
		if (mark)
			log(game.active + " moved:\n Germania \u2192 #" + to + mark + ".")
		else
			log(game.active + " moved:\n Germania \u2192 #" + to + ".")
		game.who = NOBODY
		game.state = 'move_phase'
	},
	block: pop_undo,
	undo: pop_undo,
}

states.sea_move_to = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Move Phase: Waiting for " + game.active + "."
		if (is_english_crusader(game.who))
			view.prompt = "Sea Move: Move " + block_name(game.who) + " to a port."
		else
			view.prompt = "Sea Move: Move " + block_name(game.who) + " to a friendly port."
		gen_action_undo(view)
		gen_action(view, 'block', game.who)
		let from = game.location[game.who]
		if (from === GERMANIA) {
			for (let to of GERMAN_ROADS)
				if (can_germans_move_to(game.who, to))
					gen_action(view, 'town', to)
		} else {
			for (let to of PORTS)
				if (to !== game.where && can_block_sea_move_to(game.who, to))
					gen_action(view, 'town', to)
		}
	},
	town: function (to) {
		--game.moves

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

		lift_siege(from)

		set_delete(game.castle, game.who)

		if ((to === TYRE || to === TRIPOLI) && besieged_player(to) === game.active && is_more_room_in_castle(to)) {
			// Move into besieged fortified port
			set_add(game.castle, game.who)
			log(game.active + " sea moved:")
			logi("#" + from + " \u2192 #" + to + " castle.")

		} else if (!is_friendly_port(to)) {
			// English Crusaders attack!
			game.attacker[to] = FRANKS
			set_main_road(to, ENGLAND)
			log(game.active + " sea moved:")
			logi("#" + from + " \u2192 #" + to + ATTACK_MARK + ".")

		} else {
			// Normal move.
			log(game.active + " sea moved:")
			logi("#" + from + " \u2192 #" + to + ".")
		}

		game.who = NOBODY
		game.state = 'move_phase'
	},
	block: pop_undo,
	undo: pop_undo,
}

// MUSTER

states.muster = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Move Phase: Waiting for " + game.active + "."
		view.prompt = "Muster: Choose a friendly muster town."
		gen_action_undo(view)
		for (let where = first_town; where <= last_town; ++where) {
			// cannot start or reinforce battles in winter
			if (is_winter()) {
				if (is_friendly_town(where))
					if (can_muster_to(where))
						gen_action(view, 'town', where)
			} else {
				if (is_friendly_field(where))
					if (can_muster_to(where))
						gen_action(view, 'town', where)
			}
		}
	},
	town: function (where) {
		push_undo()
		game.where = where
		game.state = 'muster_who'
		game.summary = []
	},
	undo: pop_undo,
}

states.muster_who = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Move Phase: Waiting for " + game.active + "."
		view.prompt = "Muster: Move blocks to " + town_name(game.where) + "."
		view.muster = game.where
		gen_action_undo(view)
		gen_action(view, 'end_muster')
		for (let b = 0; b <= last_block; ++b)
			if (can_block_muster(b, game.where))
				gen_action(view, 'block', b)
	},
	block: function (who) {
		push_undo()
		game.who = who
		game.state = 'muster_move_1'
	},
	end_muster: function () {
		print_summary(game.active + " mustered to #" + game.where + ":")
		game.where = NOWHERE
		game.state = 'move_phase'
	},
	undo: pop_undo,
}

states.muster_move_1 = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Move Phase: Waiting for " + game.active + "."
		view.prompt = "Muster: Move " + block_name(game.who) + " to " + town_name(game.where) + "."
		view.muster = game.where
		gen_action_undo(view)
		gen_action(view, 'block', game.who)
		let from = game.location[game.who]
		let muster = game.where
		if (block_move(game.who) === 3) {
			for (let to of TOWNS[from].exits) {
				if (can_block_use_road_to_muster(from, to)) {
					if (to === muster || can_block_muster_with_2_moves(to, muster, from))
						gen_action(view, 'town', to)
				}
			}
		} else {
			for (let to of TOWNS[from].exits) {
				if (can_block_use_road_to_muster(from, to)) {
					if (to === muster || can_block_muster_with_1_move(to, muster))
						gen_action(view, 'town', to)
				}
			}
		}
	},
	town: function (to) {
		let from = game.location[game.who]
		set_add(game.moved, game.who)
		log_move_start(from)
		log_move_continue(to)
		move_block(game.who, from, to)
		lift_siege(from)
		if (to === game.where) {
			end_muster_move()
		} else {
			game.state = 'muster_move_2'
		}
	},
	block: pop_undo,
	undo: pop_undo,
}

states.muster_move_2 = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Move Phase: Waiting for " + game.active + "."
		view.prompt = "Muster: Move " + block_name(game.who) + " to " + town_name(game.where) + "."
		view.muster = game.where
		gen_action_undo(view)
		let from = game.location[game.who]
		let muster = game.where
		if (block_move(game.who) === 3) {
			for (let to of TOWNS[from].exits) {
				if (can_block_use_road_to_muster(from, to)) {
					if (to === muster || can_block_muster_with_1_move(to, muster))
						gen_action(view, 'town', to)
				}
			}
		} else {
			for (let to of TOWNS[from].exits) {
				if (can_block_use_road_to_muster(from, to)) {
					if (to === muster)
						gen_action(view, 'town', to)
				}
			}
		}
	},
	town: function (to) {
		let from = game.location[game.who]
		log_move_continue(to)
		move_block(game.who, from, to)
		if (to === game.where) {
			end_muster_move()
		} else {
			game.state = 'muster_move_3'
		}
	},
	undo: pop_undo,
}

states.muster_move_3 = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Move Phase: Waiting for " + game.active + "."
		view.prompt = "Muster: Move " + block_name(game.who) + " to " + town_name(game.where) + "."
		view.muster = game.where
		gen_action_undo(view)
		let from = game.location[game.who]
		let muster = game.where
		for (let to of TOWNS[from].exits) {
			if (can_block_use_road_to_muster(from, to)) {
				if (to === muster)
					gen_action(view, 'town', to)
			}
		}
	},
	town: function (to) {
		let from = game.location[game.who]
		log_move_continue(to)
		move_block(game.who, from, to)
		end_muster_move()
	},
	undo: pop_undo,
}

function end_muster_move() {
	log_move_end()
	game.who = NOBODY
	game.state = 'muster_who'
}

// WINTER CAMPAIGN

states.winter_campaign = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Move Phase: Waiting for " + game.active + "."
		view.prompt = "Winter Campaign: Select a siege to maintain over the winter."
		gen_action_undo(view)
		for (let town = first_town; town <= last_town; ++town)
			if (is_friendly_field(town) && is_under_siege(town))
				gen_action(view, 'town', town)
	},
	town: function (where) {
		log(game.active + " winter campaigned at #" + where + ".")
		game.winter_campaign = where
		game.state = 'move_phase'
	},
	undo: pop_undo
}

// COMBAT PHASE

function goto_combat_phase() {
	if (is_winter()) {
		set_clear(game.moved)
		return end_game_turn()
	}

	game.combat_list = []
	for (let where = first_town; where <= last_town; ++where)
		if (is_contested_town(where))
			set_add(game.combat_list, where)
	resume_combat_phase()
}

function resume_combat_phase() {
	reset_road_limits()
	reset_moved_for_combat()

	if (game.combat_list.length > 0) {
		game.active = game.p1
		game.state = 'combat_phase'
	} else {
		goto_draw_phase()
	}
}

states.combat_phase = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Battle Phase: Waiting for " + game.active + "."
		view.prompt = "Battle Phase: Choose the next battle or siege!"
		for (let where of game.combat_list)
			gen_action(view, 'town', where)
	},
	town: function (where) {
		set_delete(game.combat_list, where)
		game.where = where
		start_combat()
	},
}

function start_combat() {
	game.flash = ""
	log("")
	log(".h3 Battle at #" + game.where)
	game.combat_round = 0
	game.halfhit = NOBODY
	game.storming = []
	game.sallying = []
	game.hits = 0

	game.show_castle = 0
	game.show_field = 0

	if (is_castle_town(game.where)) {
		if (!is_under_siege(game.where)) {
			log(".h4 Combat Deployment")
			game.castle_owner = enemy(game.attacker[game.where])
			game.active = game.castle_owner
			game.state = 'combat_deployment'
			game.is_existing_siege = 0
		} else {
			game.castle_owner = besieged_player(game.where)
			if (!game.attacker[game.where])
				game.attacker[game.where] = enemy(game.castle_owner)
			log("Existing siege continued.")
			game.is_existing_siege = 1
			next_combat_round()
		}
	} else {
		game.castle_owner = null
		next_combat_round()
	}
}

function end_combat() {
	lift_siege(game.where)

	if (game.jihad === game.where)
		game.jihad = null

	delete game.is_existing_siege
	delete game.castle_owner
	delete game.storming
	delete game.sallying
	delete game.show_castle
	delete game.show_field
	game.where = NOWHERE
	game.flash = ""
	game.combat_round = 0

	resume_combat_phase()
}

// COMBAT DEPLOYMENT

states.combat_deployment = {
	show_battle: true,
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Battle: Waiting for " + game.active + "."
		view.prompt = "Battle: Deploy blocks on the field and in the castle."
		let max = castle_limit(game.where)
		let n = count_blocks_in_castle(game.where)
		let have_options = false
		if (n < max) {
			for (let b = 0; b <= last_block; ++b) {
				if (block_owner(b) === game.active && !is_reserve(b)) {
					if (game.location[b] === game.where && !set_has(game.castle, b)) {
						gen_action(view, 'withdraw', b)
						gen_action(view, 'block', b)
						have_options = true
					}
				}
			}
		}
		if (!have_options)
			view.flash_next = "Click Next when you're done."
		gen_action_undo(view)
		gen_action(view, 'next')
	},
	withdraw: function (who) {
		push_undo()
		set_add(game.castle, who)
	},
	block: function (who) {
		push_undo()
		set_add(game.castle, who)
	},
	next: function () {
		clear_undo()
		let n = count_blocks_in_castle(game.where)
		if (n === 1)
			log(game.active + " withdrew 1 block.")
		else
			log(game.active + " withdrew " + n + " blocks.")
		game.active = game.attacker[game.where]
		if (count_enemy_in_field_and_reserve(game.where) === 0) {
			return goto_regroup()
		}
		next_combat_round()
	},
	undo: pop_undo
}

// REGROUP AFTER FIELD BATTLE/SIEGE VICTORY

function print_retreat_summary() {
	if (game.summary && game.summary.length > 0)
		print_summary("Retreated from #" + game.where + ":")
}

function goto_regroup() {
	lift_siege(game.where)
	if (!is_under_siege(game.where))
		clear_reserves() // no siege battle, reserves arrive before regroup
	reset_road_limits()
	reset_moved_for_combat()
	game.state = 'regroup'
	game.summary = []
}

states.regroup = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Regroup: Waiting for " + game.active + "."
		view.prompt = "Regroup: Choose a block to move."
		gen_action_undo(view)
		gen_action(view, 'end_regroup')
		for (let b = 0; b <= last_block; ++b) {
			if (game.location[b] === game.where) {
				if (can_block_regroup(b))
					gen_action(view, 'block', b)
			}
		}
	},
	block: function (who) {
		push_undo()
		game.who = who
		game.state = 'regroup_to'
	},
	end_regroup: function () {
		clear_undo()
		reset_road_limits()
		print_summary(game.active + " regrouped:", true)
		if (game.assassins) {
			delete game.assassins
			game.where = NOWHERE
			end_player_turn()
		}
		else if (is_winter())
			goto_winter_2()
		else if (is_contested_town(game.where))
			next_combat_round()
		else
			end_combat()
	},
	undo: pop_undo
}

states.regroup_to = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Regroup: Waiting for " + game.active + "."
		view.prompt = "Regroup: Move the block to a friendly or vacant town."
		gen_action_undo(view)
		gen_action(view, 'block', game.who)
		for (let to of TOWNS[game.where].exits)
			if (can_block_regroup_to(game.who, to))
				gen_action(view, 'town', to)
	},
	town: function (to) {
		// We can regroup while reserves are still on the way...
		set_delete(game.reserves1, game.who)
		set_delete(game.reserves2, game.who)

		let from = game.where
		game.summary.push([from, to])
		move_block(game.who, game.where, to)
		game.who = NOBODY
		game.state = 'regroup'
	},
	block: pop_undo,
	undo: pop_undo
}

// COMBAT ROUND

function next_combat_round() {
	print_retreat_summary()
	if (game.jihad === game.where && game.combat_round === 1)
		game.jihad = null
	switch (game.combat_round) {
	case 0: return goto_combat_round(1)
	case 1: return goto_combat_round(2)
	case 2: return goto_combat_round(3)
	case 3: return goto_retreat_after_combat()
	}
}

function bring_on_reserves(reserves) {
	let f = 0
	let s = 0
	for (let b = 0; b <= last_block; ++b) {
		if (game.location[b] === game.where) {
			if (set_has(reserves, b)) {
				if (block_owner(b) === FRANKS)
					++f
				else
					++s
				set_delete(reserves, b)
			}
		}
	}
	if (f > 0)
		log(f + " Frank " + (f === 1 ? "reserve arrived." : "reserves arrived."))
	if (s > 0)
		log(s + " Saracen " + (s === 1 ? "reserve arrived." : "reserves arrived."))
}

function clear_reserves(where) {
	for (let b = 0; b <= last_block; ++b) {
		if (game.location[b] === where) {
			set_delete(game.reserves1, b)
			set_delete(game.reserves2, b)
		}
	}
}

function reset_moved_for_combat() {
	set_clear(game.moved)
	for (let b of game.reserves1) set_add(game.moved, b)
	for (let b of game.reserves2) set_add(game.moved, b)
}

function goto_combat_round(new_combat_round) {
	game.combat_round = new_combat_round
	game.summary = []

	let was_contested = is_contested_battle_field()

	// If a relief force attacks besieging forces outside a castle,
	// but the besieged forces sail away and abandon the castle,
	// skip the first combat round to let the battle proceed from
	// when the reserves arrive.
	if (game.combat_round === 1 && !is_under_siege(game.where)) {
		if (!was_contested && is_contested_town(game.where)) {
			if (count_friendly_in_field_excluding_reserves(game.where) === 0) {
				log("Combat round skipped because main attack sailed away.")
				game.combat_round = 2
			}
		}
	}

	// If the main attack regroups away from a new siege while reinforcements
	// are on the way, we need to skip the first combat round.
	if (game.combat_round === 1 && is_under_siege(game.where)) {
		game.active = besieging_player(game.where)
		if (count_friendly_in_field_excluding_reserves(game.where) === 0) {
			log("Combat round skipped because main attack regrouped away.")
			game.combat_round = 2
		}
	}

	log(".h4 Combat Round " + game.combat_round)

	if (game.combat_round === 2)
		bring_on_reserves(game.reserves1)
	if (game.combat_round === 3)
		bring_on_reserves(game.reserves2)

	reset_moved_for_combat()

	if (is_contested_battle_field()) {
		if (is_under_siege(game.where)) {
			if (!was_contested) {
				log("Relief forces arrived!")
				if (game.storming.length > 0) {
					log("Storming canceled by arriving relief force.")
					game.halfhit = NOBODY
					game.storming.length = 0
				}
				let old_attacker = game.attacker[game.where]
				game.attacker[game.where] = besieged_player(game.where)
				if (old_attacker !== game.attacker[game.where]) {
					log(game.attacker[game.where] + " are now the attacker.")
				}
			}
			// No sally first round after combat deployment.
			if (game.combat_round > 1 || game.is_existing_siege)
				return goto_declare_sally()
		}
		return goto_field_battle()
	}

	goto_declare_storm()
}

// DECLARE STORM

function goto_declare_storm() {
	game.active = besieging_player(game.where)
	// Castle is full.
	if (game.storming.length === castle_limit(game.where))
		return goto_siege_battle()
	// Field is empty.
	if (count_friendly(game.where) - game.storming.length === 0)
		return goto_siege_battle()
	game.state = 'declare_storm'
}

states.declare_storm = {
	show_battle: true,
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Siege Declaration: Waiting for " + game.active + " to declare storm."
		view.prompt = "Siege Declaration: Declare which blocks should storm the castle."
		let have_options = false
		if (game.storming.length < castle_limit(game.where)) {
			for (let b = 0; b <= last_block; ++b) {
				if (block_owner(b) === game.active && !is_reserve(b)) {
					if (game.location[b] === game.where && !set_has(game.storming, b)) {
						gen_action(view, 'storm', b)
						gen_action(view, 'block', b)
						have_options = true
					}
				}
			}
		}
		if (!have_options)
			view.flash_next = "Click Next when you're done."
		gen_action_undo(view)
		gen_action(view, 'next')
	},
	storm: storm_with_block,
	block: storm_with_block,
	next: function () {
		clear_undo()
		let n = game.storming.length
		if (n === 0) {
			game.flash = game.active + " declined to storm."
			if (game.jihad === game.where)
				game.jihad = null
			log(game.active + " declined to storm.")
			goto_declare_sally()
		} else {
			goto_siege_battle()
		}
	},
	undo: pop_undo
}

function storm_with_block(who) {
	push_undo()
	set_add(game.storming, who)
	if (game.storming.length > 1)
		game.flash = game.active + " stormed with " + game.storming.length + " blocks."
	else
		game.flash = game.active + " stormed with 1 block."
	log(game.active[0] + ": " + block_name(who) + " stormed.")
}

// DECLARE SALLY

function goto_declare_sally() {
	game.active = besieged_player(game.where)
	game.state = 'declare_sally'
	game.was_contested = is_contested_battle_field()
}

states.declare_sally = {
	show_battle: true,
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Siege Declaration: Waiting for " + game.active + " to declare sally."
		view.prompt = "Siege Declaration: Declare which blocks should sally onto the field."
		let have_options = false
		for (let b = 0; b <= last_block; ++b) {
			if (block_owner(b) === game.active && !is_reserve(b) && is_block_in_castle(b)) {
				if (game.location[b] === game.where && !set_has(game.sallying, b)) {
					gen_action(view, 'sally', b)
					gen_action(view, 'block', b)
					have_options = true
				}
			}
		}
		if (!have_options)
			view.flash_next = "Click Next when you're done."
		gen_action_undo(view)
		gen_action(view, 'next')
	},
	sally: sally_with_block,
	block: sally_with_block,
	next: function () {
		clear_undo()
		let n = game.sallying.length
		if (n === 0) {
			game.flash = game.active + " declined to sally."
			log(game.active + " declined to sally.")
		}
		if (is_contested_battle_field()) {
			if (!game.was_contested) {
				log(game.active + " are now the attacker.")
				game.attacker[game.where] = game.active
			}
			goto_field_battle()
		} else if (count_reserves(game.where) > 0) {
			next_combat_round()
		} else {
			goto_siege_attrition()
		}
	},
	undo: pop_undo
}

function sally_with_block(who) {
	push_undo()
	set_delete(game.castle, who)
	set_add(game.sallying, who)
	if (game.sallying.length > 1)
		game.flash = game.active + " sallied with " + game.sallying.length + " blocks."
	else
		game.flash = game.active + " sallied with 1 block."
	log(game.active[0] + ": " + block_name(who) + " sallied.")
}

// RETREAT AFTER COMBAT

function goto_retreat_after_combat() {
	reset_moved_for_combat()

	// withdraw all sallying blocks to castle.
	for (let b of game.sallying)
		set_add(game.castle, b)
	game.sallying.length = 0

	// TODO: 6.2 - In Sieges, the attacker /may/ retreat or stay on siege.

	// withdraw all storming blocks to the field.
	game.halfhit = NOBODY
	game.storming.length = 0

	if (is_contested_field(game.where)) {
		log(".h4 Retreat")
		game.active = game.attacker[game.where]
		game.state = 'retreat'
		game.summary = []
	} else if (is_under_siege(game.where)) {
		goto_siege_attrition()
	} else {
		end_combat()
	}
}

states.retreat = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Retreat: Waiting for " + game.active + "."
		view.prompt = "Retreat: Choose a block to move."
		gen_action_undo(view)
		let can_retreat = false
		for (let b = 0; b <= last_block; ++b) {
			if (game.location[b] === game.where && !is_block_in_castle(b) && can_block_retreat(b)) {
				gen_action(view, 'block', b)
				can_retreat = true
			}
		}
		if (!is_contested_field(game.where) || !can_retreat)
			gen_action(view, 'end_retreat')
	},
	end_retreat: function () {
		clear_undo()
		for (let b = 0; b <= last_block; ++b)
			if (game.location[b] === game.where && !is_block_in_castle(b) && block_owner(b) === game.active)
				eliminate_block(b)
		print_summary(game.active + " retreated:")
		game.active = enemy(game.active)
		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 = "Retreat: Waiting for " + game.active + "."
		view.prompt = "Retreat: Move the block to a friendly or neutral town."
		gen_action_undo(view)
		gen_action(view, 'block', game.who)
		let can_retreat = false
		for (let to of TOWNS[game.where].exits) {
			if (can_block_retreat_to(game.who, to)) {
				gen_action(view, 'town', to)
				can_retreat = true
			}
		}
		if (!can_retreat)
			gen_action(view, 'eliminate')
	},
	town: function (to) {
		let from = game.where
		game.summary.push([from, to])
		move_block(game.who, game.where, to)
		game.who = NOBODY
		game.state = 'retreat'
	},
	eliminate: function () {
		eliminate_block(game.who)
		game.who = NOBODY
		game.state = 'retreat'
	},
	block: pop_undo,
	undo: pop_undo
}

// SIEGE ATTRITION

function goto_siege_attrition() {
	log(".h4 Siege Attrition")
	game.active = besieged_player(game.where)
	game.state = 'siege_attrition'
	game.attrition_list = []
	for (let b = 0; b <= last_block; ++b)
		if (is_block_in_castle_in(b, game.where))
			set_add(game.attrition_list, b)
}

function resume_siege_attrition() {
	if (game.attrition_list.length === 0) {
		delete game.attrition_list
		if (!is_under_siege(game.where)) {
			game.active = enemy(game.active)
			log("#" + game.where + " fell to siege attrition.")
			goto_regroup()
		} else {
			log("Siege continued.")
			end_combat()
		}
	}
}

states.siege_attrition = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Siege Attrition: Waiting for " + game.active + "."
		view.prompt = "Siege Attrition: Roll for siege attrition in " + town_name(game.where) + "."
		for (let b of game.attrition_list)
			gen_action(view, 'block', b)
	},
	block: function (who) {
		let target = (game.where === TYRE || game.where === TRIPOLI) ? 1 : 3
		let die = roll_d6()
		if (die <= target) {
			log("Attrition roll " + DIE_HIT[die] + ".")
			reduce_block(who)
		} else {
			log("Attrition roll " + DIE_MISS[die] + ".")
		}
		set_delete(game.attrition_list, who)
		resume_siege_attrition()
	}
}

// FIELD AND SIEGE BATTLE HELPERS

function count_enemy_hp_in_field() {
	let hp = 0
	for (let b = 0; b <= last_block; ++b)
		if (block_owner(b) !== game.active && is_field_combatant(b))
			hp += game.steps[b]
	return hp
}

function count_enemy_hp_in_siege() {
	let hp = 0
	for (let b = 0; b <= last_block; ++b)
		if (block_owner(b) !== game.active && is_siege_combatant(b))
			if (is_block_in_castle(b))
				hp += game.steps[b] * 2
			else
				hp += game.steps[b]
	if (game.halfhit !== NOBODY && block_owner(game.halfhit) !== game.active)
		hp -= 1
	return hp
}

function must_apply_field_hits() {
	if (game.immediate)
		return game.hits > 0
	return game.hits >= count_enemy_hp_in_field()
}

function must_apply_siege_hits() {
	if (game.immediate)
		return game.hits > 0
	return game.hits >= count_enemy_hp_in_siege()
}

function filter_battle_blocks(ci, is_candidate) {
	let output = null
	for (let b = 0; b <= last_block; ++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 false
}

function goto_battle_hits() {
	if (game.state === 'field_battle')
		goto_field_battle_hits()
	else if (game.state === 'siege_battle')
		goto_siege_battle_hits()
	else
		throw new Error("invalid battle state")
}

function pump_battle_step(is_candidate_attacker, is_candidate_defender) {
	let attacker = game.attacker[game.where]
	let defender = enemy(attacker)

	if (game.jihad === game.where && game.combat_round === 1) {
		if (battle_step(attacker, 'A', is_candidate_attacker)) return
		if (battle_step(attacker, 'B', is_candidate_attacker)) return
		if (battle_step(attacker, 'C', is_candidate_attacker)) return
		if (battle_step(defender, 'A', is_candidate_defender)) return
		if (battle_step(defender, 'B', is_candidate_defender)) return
		if (battle_step(defender, 'C', is_candidate_defender)) return
	} else {
		if (battle_step(defender, 'A', is_candidate_defender)) return
		if (battle_step(attacker, 'A', is_candidate_attacker)) return
		if (battle_step(defender, 'B', is_candidate_defender)) return
		if (battle_step(attacker, 'B', is_candidate_attacker)) return
		if (battle_step(defender, 'C', is_candidate_defender)) return
		if (battle_step(attacker, 'C', is_candidate_attacker)) return
	}

	if (game.hits > 0) {
		game.active = enemy(game.active)
		return goto_battle_hits()
	}

	next_combat_round()
}

// FIELD BATTLE

function goto_field_battle() {
	resume_field_battle()
}

function resume_field_battle() {
	// we have a queued up harry action
	if (game.harry) {
		game.active = game.harry
		game.state = 'harry'
		delete game.harry
		return
	}

	let save_active = game.active
	game.active = game.attacker[game.where]

	if (is_friendly_field(game.where)) {
		if (game.hits > 0) {
			game.active = enemy(save_active)
			return goto_field_battle_hits()
		}
		print_retreat_summary()
		log("Field battle won by " + game.active + ".")
		game.show_field = 0
		return goto_regroup()
	}

	if (is_enemy_field(game.where)) {
		if (game.hits > 0) {
			game.active = enemy(save_active)
			return goto_field_battle_hits()
		}
		game.active = enemy(game.active)
		print_retreat_summary()
		log("Field battle won by " + game.active + ".")
		game.show_field = 0
		return goto_regroup()
	}

	if (is_enemy_battle_field()) {
		if (game.hits > 0) {
			game.active = enemy(save_active)
			return goto_field_battle_hits()
		}
		print_retreat_summary()
		log("Attacking main force was eliminated.")
		return next_combat_round()
	}

	if (is_friendly_battle_field()) {
		if (game.hits > 0) {
			game.active = enemy(save_active)
			return goto_field_battle_hits()
		}
		print_retreat_summary()
		log("Defending main force was eliminated.")
		log("Battlefield control changed.")
		game.attacker[game.where] = enemy(game.active)
		// The new defender takes control of the empty castle
		if (!is_under_siege(game.where))
			game.castle_owner = game.active
		return next_combat_round()
	}

	game.active = save_active
	game.state = 'field_battle'
	game.show_field = 1
	pump_battle_step(is_field_attacker, is_field_defender)
}

states.field_battle = {
	show_battle: true,
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Field Battle: Waiting for " + game.active + "."
		view.prompt = "Field Battle: Choose a combat action."
		for (let b of game.battle_list) {
			gen_action(view, 'block', b) // take default action
			gen_action(view, 'fire', b)
			if (set_has(game.sallying, b)) {
				// Only sallying forces may withdraw into the castle
				gen_action(view, 'withdraw', b)
			} else {
				if (can_block_retreat(b)) {
					gen_action(view, 'retreat', b)
					// Turcopoles and Nomads can Harry (fire and retreat)
					if (block_type(b) === 'turcopoles' || block_type(b) === 'nomads')
						gen_action(view, 'harry', b)
				}

				// Defender can withdraw into castle if friendly and there is room.
				if (game.active !== game.attacker[game.where] && game.active === game.castle_owner) {
					// TODO: allow swapping place of sallying block, leaving it to die if it cannot withdraw?
					if (game.sallying.length + count_blocks_in_castle(game.where) < castle_limit(game.where))
						gen_action(view, 'withdraw', b)
				}
			}
			// All Frank B blocks are knights who can Charge
			if (block_owner(b) === FRANKS && block_initiative(b) === 'B')
				gen_action(view, 'charge', 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_field_battle_hits()
	},
	block: field_fire_with_block,
	fire: field_fire_with_block,
	withdraw: field_withdraw_with_block,
	charge: charge_with_block,
	harry: harry_with_block,
	retreat: retreat_with_block,
}

// SIEGE BATTLE

function goto_siege_battle() {
	game.attacker[game.where] = besieging_player(game.where)
	game.show_castle = 1
	resume_siege_battle()
}

function resume_siege_battle() {
	let save_active = game.active
	game.active = game.attacker[game.where]

	if (is_friendly_town(game.where)) {
		log("Siege battle won by " + game.active + ".")
		return goto_regroup()
	}

	if (is_enemy_town(game.where)) {
		game.active = enemy(game.active)
		game.halfhit = NOBODY
		log("Siege battle won by " + game.active + ".")
		return goto_regroup()
	}

	if (count_blocks_in_castle(game.where) === 0) {
		log("Defending main force was eliminated.")
		log(game.active + " are now the defender.")
		game.attacker[game.where] = enemy(game.active)
		// The new defender takes control of the empty castle
		game.castle_owner = game.active
		game.storming.length = 0
		return next_combat_round()
	}

	if (game.storming.length === 0) {
		game.halfhit = NOBODY
		log("Storming repulsed.")
		return next_combat_round()
	}

	game.active = save_active
	game.state = 'siege_battle'
	pump_battle_step(is_siege_attacker, is_siege_defender)
}

states.siege_battle = {
	show_battle: true,
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Siege Battle: Waiting for " + game.active + "."
		view.prompt = "Siege Battle: Choose a combat action."
		for (let b of game.battle_list) {
			gen_action(view, 'block', b) // take default action
			gen_action(view, 'fire', b)
			if (set_has(game.storming, b))
				gen_action(view, '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_siege_battle_hits()
	},
	block: siege_fire_with_block,
	fire: siege_fire_with_block,
	retreat: siege_withdraw_with_block,
}

// FIELD BATTLE HITS

function goto_field_battle_hits() {
	game.battle_list = list_field_victims()
	if (game.battle_list.length === 0) {
		game.hits = 0
		resume_field_battle()
	} else {
		game.state = 'field_battle_hits'
	}
}

function list_field_victims() {
	let max = 0
	for (let b = 0; b <= last_block; ++b)
		if (block_owner(b) === game.active && is_field_combatant(b) && game.steps[b] > max)
			max = game.steps[b]
	let list = []
	for (let b = 0; b <= last_block; ++b)
		if (block_owner(b) === game.active && is_field_combatant(b) && game.steps[b] === max)
			list.push(b)
	return list
}

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

function apply_field_battle_hit_to(who, flash) {
	let msg
	msg = block_name(who) + " took a hit."
	log(game.active[0] + ": " + msg)
	if (flash)
		game.flash = msg
	reduce_block(who)
	game.hits--
}

function apply_field_battle_hit(who) {
	apply_field_battle_hit_to(who, true)
	if (game.hits === 0)
		resume_field_battle()
	else {
		game.battle_list = list_field_victims()
		if (game.battle_list.length === 0) {
			game.hits = 0
			resume_field_battle()
		} else {
			game.flash += " " + game.hits + (game.hits === 1 ? " hit left." : " hits left.")
		}
	}
}

// SIEGE BATTLE HITS

function goto_siege_battle_hits() {
	game.battle_list = list_siege_victims()
	if (game.battle_list.length === 0) {
		game.hits = 0
		resume_siege_battle()
	} else {
		game.state = 'siege_battle_hits'
	}
}

function list_siege_victims() {
	if (game.halfhit !== NOBODY && block_owner(game.halfhit) === game.active)
		return [ game.halfhit ]
	let max = 0
	for (let b = 0; b <= last_block; ++b)
		if (block_owner(b) === game.active && is_siege_combatant(b) && game.steps[b] > max)
			max = game.steps[b]
	let list = []
	for (let b = 0; b <= last_block; ++b)
		if (block_owner(b) === game.active && is_siege_combatant(b) && game.steps[b] === max)
			list.push(b)
	return list
}

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

function apply_siege_battle_hit_to(who, flash) {
	let msg = block_name(who) + " took a "
	if (game.halfhit === who) {
		msg += "hit."
		log(game.active[0] + ": " + msg)
		reduce_block(who)
		game.halfhit = NOBODY
	} else {
		if (is_block_in_castle(who)) {
			msg += "half-hit."
			log(game.active[0] + ": " + msg)
			game.halfhit = who
		} else {
			msg += "hit."
			log(game.active[0] + ": " + msg)
			reduce_block(who)
		}
	}
	if (flash)
		game.flash = msg
	game.hits--
}

function apply_siege_battle_hit(who) {
	apply_siege_battle_hit_to(who, true)
	if (game.hits === 0) {
		resume_siege_battle()
	} else {
		game.battle_list = list_siege_victims()
		if (game.battle_list.length === 0) {
			game.hits = 0
			resume_siege_battle()
		} else {
			game.flash += " " + game.hits + (game.hits === 1 ? " hit left." : " hits left.")
		}
	}
}

// BATTLE ACTIONS

function roll_attack(active, b, verb, is_charge) {
	let fire = block_fire_power(b, game.where) + is_charge
	let steps = game.steps[b]
	let name = block_name(b) + " " + BLOCKS[b].initiative + BLOCKS[b].fire_power

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

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

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

	if (self > 0) {
		if (self === 1)
			game.flash += " " + self + " self hit."
		else
			game.flash += " " + self + " self hits."
		self = Math.min(self, game.steps[b])
		while (self-- > 0)
			reduce_block(b)
	}
}

function field_fire_with_block(b) {
	set_add(game.moved, b)
	roll_attack(game.active, b, "fired", 0)
	if (must_apply_field_hits()) {
		game.active = enemy(game.active)
		goto_field_battle_hits()
	} else {
		resume_field_battle()
	}
}

function siege_fire_with_block(b) {
	set_add(game.moved, b)
	roll_attack(game.active, b, "fired", 0)
	if (must_apply_siege_hits()) {
		game.active = enemy(game.active)
		goto_siege_battle_hits()
	} else {
		resume_siege_battle()
	}
}

function charge_with_block(b) {
	set_add(game.moved, b)
	roll_attack(game.active, b, "charged", 1)
	if (must_apply_field_hits()) {
		game.active = enemy(game.active)
		goto_field_battle_hits()
	} else {
		resume_field_battle()
	}
}

function field_withdraw_with_block(b) {
	game.flash = block_name(b) + " withdrew."
	log(game.active[0] + ": " + game.flash)
	set_add(game.moved, b)
	set_delete(game.sallying, b)
	set_add(game.castle, b)
	resume_field_battle()
}

function siege_withdraw_with_block(b) {
	game.flash = block_name(b) + " withdrew."
	log(game.active[0] + ": " + game.flash)
	set_add(game.moved, b)
	set_delete(game.storming, b)
	resume_siege_battle()
}

function harry_with_block(b) {
	game.harry = game.active // remember to retreat after hits have been applied
	game.who = b
	roll_attack(game.active, b, "harried", 0)
	if (must_apply_field_hits()) {
		game.active = enemy(game.active)
		goto_field_battle_hits()
	} else {
		resume_field_battle()
	}
}

states.harry = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Field Battle: Waiting for " + game.active + " to retreat the harrying block."
		view.prompt = "Field Battle: Retreat the harrying block to a friendly or vacant town."
		for (let to of TOWNS[game.where].exits)
			if (can_block_retreat_to(game.who, to))
				gen_action(view, 'town', to)
	},
	town: function (to) {
		game.flash += " " + block_name(game.who) + " retreated."
		game.summary.push([game.active, to])
		game.location[game.who] = to
		move_block(game.who, game.where, to)
		game.who = NOBODY
		resume_field_battle()
	},
}

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

states.retreat_in_battle = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Field Battle: Waiting for " + game.active + " to retreat."
		gen_action(view, 'undo')
		gen_action(view, 'block', game.who)
		view.prompt = "Field Battle: Retreat the block to a friendly or vacant town."
		for (let to of TOWNS[game.where].exits)
			if (can_block_retreat_to(game.who, to))
				gen_action(view, 'town', to)
	},
	town: function (to) {
		game.flash = block_name(game.who) + " retreated."
		log(game.active[0] + ": " + game.flash)
		game.summary.push([game.active, to])
		game.location[game.who] = to
		move_block(game.who, game.where, to)
		game.who = NOBODY
		resume_field_battle()
	},
	block: function () {
		game.who = NOBODY
		resume_field_battle()
	},
	undo: function () {
		game.who = NOBODY
		resume_field_battle()
	}
}

// DRAW PHASE

function goto_draw_phase() {
	delete game.combat_list
	if (game.year > 1187 && !is_winter()) {
		game.active = game.p1
		log("")
		start_draw_phase()
	} else {
		end_game_turn()
	}
}

function start_draw_phase() {
	game.state = 'draw_phase'
	if (game.active === FRANKS) {
		game.who = select_random_block(F_POOL)
		if (game.who === NOBODY)
			end_draw_phase()
	} else {
		game.who = select_random_block(S_POOL)
		if (game.who === NOBODY)
			end_draw_phase()
	}
}

states.draw_phase = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Draw Phase: Waiting for " + game.active + "."
		let can_place = false
		switch (block_type(game.who)) {
		case 'crusaders':
			view.prompt = "Draw Phase: Place " + block_name(game.who) + " in the staging area."
			gen_action(view, 'town', block_home(game.who))
			can_place = true
			break
		case 'pilgrims':
			view.prompt = "Draw Phase: Place " + block_name(game.who) + " in a friendly port."
			for (let town = first_town; town <= last_town; ++town) {
				if (is_friendly_port(town) || can_enter_besieged_port(town)) {
					gen_action(view, 'town', town)
					can_place = true
				}
			}
			break
		case 'turcopoles':
		case 'outremers':
		case 'emirs':
		case 'nomads':
			view.prompt = "Draw Phase: Place " + block_name(game.who) + " at full strength in "
				+ block_seat_names[game.who] + " or at strength 1 in any friendly town."
			for (let town = first_town; town <= last_town; ++town) {
				if (town === ENGLAND || town === FRANCE || town === GERMANIA)
					continue
				if (is_friendly_town(town)) {
					if (set_has(block_seats[game.who], town))
						gen_action(view, 'town', town)
					else
						gen_action(view, 'townb', town)
					can_place = true
				}
			}
			break
		}
		if (!can_place)
			gen_action(view, 'next')
	},
	townb: function (where) {
		this.town(where)
	},
	town: function (where) {
		let type = block_type(game.who)

		log(game.active + " deployed at #" + where + ".")

		game.location[game.who] = where
		if (type === 'turcopoles' || type === 'outremers' || type === 'emirs' || type === 'nomads') {
			if (is_home_seat(where, game.who))
				game.steps[game.who] = block_max_steps(game.who)
			else
				game.steps[game.who] = 1
		} else {
			game.steps[game.who] = block_max_steps(game.who)
			if (can_enter_besieged_port(where))
				set_add(game.castle, game.who)
		}

		game.who = NOBODY
		end_draw_phase()
	},
	next: function () {
		end_draw_phase()
	},
}

function end_draw_phase() {
	if (game.active === game.p1) {
		game.active = game.p2
		start_draw_phase()
	} else {
		end_game_turn()
	}
}

function end_game_turn() {
	if (is_winter()) {
		goto_winter_1()
	} else {
		if (check_sudden_death())
			return
		game.turn ++
		start_game_turn()
	}
}

// WINTER CAMPAIGN & SUPPLY

function goto_winter_1() {
	log("")
	log(".h1 Winter of " + game.year)
	log("")
	if (game.winter_campaign)
		goto_winter_siege_attrition()
	else
		goto_winter_2()
}

function goto_winter_siege_attrition() {
	log(game.active + " winter campaigned at #" + game.winter_campaign + ".")
	game.where = game.winter_campaign

	game.active = besieged_player(game.where)
	game.state = 'winter_siege_attrition'
	game.attrition_list = []
	for (let b = 0; b <= last_block; ++b)
		if (is_block_in_castle_in(b, game.where))
			set_add(game.attrition_list, b)
}

function resume_winter_siege_attrition() {
	if (game.attrition_list.length === 0) {
		delete game.attrition_list
		if (!is_under_siege(game.where)) {
			game.active = enemy(game.active)
			log("#" + game.where + " fell to siege attrition.")
			goto_regroup()
		} else {
			log("Siege continued.")
			goto_winter_2()
		}
	}
}

states.winter_siege_attrition = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Winter Siege Attrition: Waiting for " + game.active + "."
		view.prompt = "Winter Siege Attrition: Roll for siege attrition in " + town_name(game.where) + "."
		for (let b of game.attrition_list)
			gen_action(view, 'block', b)
	},
	block: function (who) {
		let target = (game.where === TYRE || game.where === TRIPOLI) ? 2 : 4
		let die = roll_d6()
		if (die <= target) {
			log("Attrition roll " + DIE_HIT[die] + ".")
			reduce_block(who)
		} else {
			log("Attrition roll " + DIE_MISS[die] + ".")
		}
		set_delete(game.attrition_list, who)
		resume_winter_siege_attrition()
	}
}

function goto_winter_2() {
	game.where = NOWHERE
	eliminate_besieging_blocks(FRANKS)
	eliminate_besieging_blocks(SARACENS)
	lift_all_sieges()
	if (check_sudden_death())
		return
	if (game.year === 1192)
		return goto_year_end()
	goto_winter_supply()
}

function eliminate_besieging_blocks(owner) {
	game.summary = []
	for (let b = 0; b <= last_block; ++b) {
		if (block_owner(b) === owner) {
			let where = game.location[b]
			if (where === game.winter_campaign)
				continue
			if (is_block_on_land(b) && is_under_siege(where))
				if (block_owner(b) === besieging_player(where))
					disband(b)
		}
	}
	if (game.summary.length > 0)
		print_summary(owner + " disbanded sieges:")
	else
		game.summary = null
}

function need_winter_supply_check() {
	for (let town = first_town; town <= last_town; ++town) {
		if (town === game.winter_campaign)
			continue
		if (is_friendly_town(town) && !is_within_castle_limit(town))
			return true
	}
	return false
}

function goto_winter_supply() {
	game.active = FRANKS
	if (need_winter_supply_check()) {
		game.state = 'winter_supply'
		game.summary = []
	} else {
		game.active = SARACENS
		if (need_winter_supply_check()) {
			game.state = 'winter_supply'
			game.summary = []
		} else {
			game.active = FRANKS
			goto_winter_replacements()
		}
	}
}

states.winter_supply = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Winter Supply: Waiting for " + game.active + "."
		gen_action_undo(view)
		let okay_to_end = true
		for (let b = 0; b <= last_block; ++b) {
			if (block_owner(b) === game.active) {
				if (is_block_on_land(b)) {
					let where = game.location[b]
					if (where === game.winter_campaign)
						continue
					if (!is_within_castle_limit(where)) {
						gen_action(view, 'block', b)
						okay_to_end = false
					}
				}
			}
		}
		if (okay_to_end) {
			view.prompt = "Winter Supply: Disband excess blocks \u2014 done."
			gen_action(view, 'next')
		} else {
			view.prompt = "Winter Supply: Disband excess blocks."
		}
	},
	block: function (who) {
		push_undo()
		disband(who)
	},
	next: function () {
		clear_undo()
		if (game.summary.length > 0)
			print_summary(game.active + " disbanded:")
		if (game.active === FRANKS) {
			game.active = SARACENS
			game.summary = []
		} else {
			game.active = FRANKS
			goto_winter_replacements()
		}
	},
	undo: pop_undo
}

// WINTER REPLACEMENTS

function goto_winter_replacements() {
	game.rp = {}

	for (let town = first_town; town <= last_town; ++town)
		if (is_under_siege(town))
			game.rp[town] = 0
		else
			game.rp[town] = castle_limit(town)

	game.summary = []
	game.state = 'winter_replacements'
}

function replacement_cost(where) {
	let region = TOWNS[where].region
	if (KINGDOMS[region] === game.active)
		return 1
	return 2
}

states.winter_replacements = {
	prompt: function (view, current) {
		if (is_inactive_player(current))
			return view.prompt = "Winter Replacements: Waiting for " + game.active + "."
		view.prompt = "Winter Replacements: Distribute replacement points."
		gen_action_undo(view)
		let okay_to_end = true
		for (let b = 0; b <= last_block; ++b) {
			if (block_owner(b) === game.active && is_block_on_land(b)) {
				let where = game.location[b]
				let cost = replacement_cost(where)
				if (is_friendly_town(where) && game.rp[where] >= cost) {
					if (game.steps[b] < block_max_steps(b)) {
						gen_action(view, 'block', b)
						okay_to_end = false
					}
				}
			}
		}
		if (okay_to_end) {
			view.prompt = "Winter Replacements: Distribute replacement points \u2014 done."
			gen_action(view, 'next')
		} else {
			view.prompt = "Winter Replacements: Distribute replacement points."
		}
	},
	block: function (who) {
		push_undo()
		let where = game.location[who]
		let cost = replacement_cost(where)
		game.summary.push([where])
		game.steps[who] ++
		game.rp[where] -= cost
	},
	next: function () {
		clear_undo()
		end_winter_replacements()
	},
	undo: pop_undo
}

function end_winter_replacements() {
	print_summary(active_adjective() + " replacements:")
	if (game.active === FRANKS) {
		game.active = SARACENS
		game.summary = []
	} else {
		goto_year_end()
	}
}

function goto_year_end() {
	if (game.year === 1192) {
		game.state = 'game_over'
		let f_vp = count_victory_points(FRANKS)
		let s_vp = count_victory_points(SARACENS)
		if (f_vp > s_vp) {
			game.result = FRANKS
			game.victory = "Franks won!"
		} else if (f_vp < s_vp) {
			game.victory = "Saracens won!"
			game.result = SARACENS
		} else {
			game.victory = "The game ended in a draw."
			game.result = "Draw"
		}
		log("")
		log(game.victory)
		return
	}

	// Return eliminated blocks to pool.
	for (let b = 0; b <= last_block; ++b)
		if (game.location[b] === DEAD)
			game.location[b] = block_pool(b)

	game.year ++
	start_year()
}

// GAME OVER

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

// SETUP

function setup_game() {
	reset_blocks()
	game.year = 1187
	game.turn = 0
	for (let b = 0; b <= last_block; ++b) {
		if (block_owner(b) === FRANKS) {
			switch (block_type(b)) {
			case 'pilgrims':
				deploy(b, block_pool(b))
				break
			case 'crusaders':
				deploy(b, block_pool(b))
				break
			default:
				deploy(b, block_home(b))
				break
			}
		}
		if (block_owner(b) === SARACENS) {
			if (block_type(b) === 'emirs')
				deploy(b, block_home(b))
			if (block_type(b) === 'nomads')
				deploy(b, block_pool(b))
		}
	}
	deploy(ASSASSINS, MASYAF)
	goto_frank_deployment()
}

// VIEW

function make_battle_view() {
	let battle = {
		FR: [], FC: [], FF: [],
		SR: [], SC: [], SF: [],
		FCS: (game.castle_owner === FRANKS) ? castle_limit(game.where) : 0,
		SCS: (game.castle_owner === SARACENS) ? castle_limit(game.where) : 0,
		storming: game.storming,
		sallying: game.sallying,
		halfhit: game.halfhit,
		flash: game.flash,
		round: game.combat_round,
		show_castle: game.show_castle,
		show_field: game.show_field,
		town: game.where,
	}

	if (is_under_siege(game.where) && !is_contested_battle_field(game.where))
		battle.title = enemy(game.castle_owner) + " besiege " + town_name(game.where)
	else
		battle.title = game.attacker[game.where] + " attack " + town_name(game.where)
	if (game.combat_round === 0)
		battle.title += " \u2014 Combat Deployment"
	else
		battle.title += " \u2014 Round " + game.combat_round + " of 3"
	if (game.where === game.jihad)
		battle.title += " \u2014 Jihad!"

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

	fill_cell(battle.FR, FRANKS, b => is_reserve(b))
	fill_cell(battle.FC, FRANKS, b => is_block_in_castle(b))
	fill_cell(battle.FF, FRANKS, b => is_block_in_field(b) && !set_has(game.storming, b))
	fill_cell(battle.FF, SARACENS, b => is_block_in_field(b) && set_has(game.storming, b))
	fill_cell(battle.SF, FRANKS, b => is_block_in_field(b) && set_has(game.storming, b))
	fill_cell(battle.SF, SARACENS, b => is_block_in_field(b) && !set_has(game.storming, b))
	fill_cell(battle.SC, SARACENS, b => is_block_in_castle(b))
	fill_cell(battle.SR, SARACENS, b => is_reserve(b))

	return battle
}

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

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

		show_cards: false,
		s_hand: [],
		f_hand: [],
		s_card: 0,
		f_card: 0,

		location: [],
		steps: [],

		attacker: {},
		road_limit: [],
		last_used: [],

		castle: [],
		main_road: [],
		moved: [],
		reserves1: [],
		reserves2: [],
	}

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

	log(".h1 Crusader Rex")
	log("")

	if (options && options.iron_bridge) {
		game.iron_bridge = 1
		log("Iron Bridge:\nThe road between Antioch and Harim has a move limit of 3.")
		log("")
	}

	if (options && options.immediate)
		game.immediate = 1

	setup_game()
	return game
}

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

function make_siege_view() {
	let list = {}
	for (let town = first_town; town <= last_town; ++town)
		if (is_under_siege(town))
			list[town] = besieging_player(town)
	return list
}

function observer_hand() {
	let hand = []
	hand.length = Math.max(game.s_hand.length, game.f_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: game.turn,
		active: game.active,
		p1: game.p1,
		f_vp: count_victory_points(FRANKS),
		s_vp: count_victory_points(SARACENS),
		f_card: (game.show_cards || current === FRANKS) ? game.f_card : 0,
		s_card: (game.show_cards || current === SARACENS) ? game.s_card : 0,
		hand: (current === FRANKS) ? game.f_hand : (current === SARACENS) ? game.s_hand : observer_hand(),
		who: (game.active === current) ? game.who : NOBODY,
		location: game.location,
		castle: game.castle,
		steps: game.steps,
		moved: game.moved,
		sieges: make_siege_view(),
		last_used: game.last_used,
		road_limit: game.road_limit,
		battle: null,
		prompt: null,
	}

	if (game.jihad && game.jihad !== game.p1)
		view.jihad = game.jihad
	if (game.winter_campaign && game.winter_campaign !== game.p1 && game.winter_campaign !== game.p2)
		view.winter_campaign = game.winter_campaign

	if (game.main_road && game.main_road.length > 0) {
		view.main_road = []
		for (let i = 0; i < game.main_road.length; i += 2)
			if (game.main_road[i+1] !== ENGLAND)
				set_add(view.main_road, road_id(game.main_road[i+0], game.main_road[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
}