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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
const.AnimChannel_RightHandGrip = 2
const.AnimChannel_Pain = 3
const.PathTurnAnimChnl = 4
--const.AnimChannel_VerticalGrip

const.PainAnimWeight = 1000
const.PainAnimGrazingWeight = 300
const.PainAnimWeightMoment = 100
local PainEasing = GetEasingIndex("Sin in/out")

const.StopAnimCrossfadeTime = 400

DefineConstInt("Camera", "BufferSizeNoCameraMov", 30, 1, "Defines how much buffer (100% - the_value % from each side) of the screen will NOT be taken into account when deciding if camera should snap from one point to another.")

if FirstLoad then
	g_LocPollyActors = {
		{ value = "Nicole", text = "Nicole (female)", },
		{ value = "Amy", text = "Amy (female)", },
		{ value = "Emma", text = "Emma (female)", },
		{ value = "Aditi", text = "Aditi (female)", },
		{ value = "Raveena", text = "Raveena (female)", },
		{ value = "Joanna", text = "Joanna (female)", },
		{ value = "Kendra", text = "Kendra (female)", },
		{ value = "Kimberly", text = "Kimberly (female)", },
		{ value = "Salli", text = "Salli (female)", },
		-- { value = "Tatyana", text = "Tatyana (female)", }, -- disabled because other Russian-accent voice, Maxim below, produces garbled voice, don't use without checking it it's fixed by Amazon
		{ value = "Russell", text = "Russell (male)", },
		{ value = "Brian", text = "Brian (male)", },
		{ value = "Joey", text = "Joey (male)", },
		{ value = "Matthew", text = "Matthew (male)", },
		{ value = "Geraint", text = "Geraint (male)", },
		-- { value = "Maxim", text = "Maxim (male)" }, -- produces garbled voice, don't use without checking it it's fixed by Amazon
		{ value = "Ivy", text = "Ivy (child)", },
		{ value = "Justin", text = "Justin (child)", },
	}
	g_LocPollyActorsMatchTable = {}
	g_StanceActionDefault = "do not change"
end

local RandomWalkAnimBehaviors = {
	["Visit"] = true,
	["Roam"] = true,
	["RoamSingle"] = true,
	["Ambient"] = true,
}

HpToText = {
	Hidden = T{""},
	Dead = T(541985975283, "Dead"),
	Dying = T(179713645915, "Almost dead"),
	Critical = T(127741862032, "Severely Wounded"),
	Wounded = T(811971736433, "Wounded"),
	Poor = T(121790238609, "Weak"),
	Healthy = T(150774995803, "Healthy"),
	Strong = T(830864531146, "Strong"),
	Excellent = T(341748793018, "Very strong"),
	Uninjured = T(586026778443, "Uninjured"),
}

DieChanceToText = {
	None = T(971598159331, --[[chance to die]] "None"),
	Low = T(283826279782, --[[chance to die]] "Low"),
	Moderate = T(904355103349, --[[chance to die]] "Moderate"),
	High = T(295409078209, --[[chance to die]] "High"),
	VeryHigh = T(426026245987, --[[chance to die]] "Very High"),
}

local KeepAimIKCommands = {
	Idle = true,
	AimIdle = true,
	OpportunityAttack = true,
	PreparedAttackIdle = true,
	ExecFirearmAttacks = true,
	HeavyWeaponAttack = true,
	FirearmAttack = true,
}

DefineClass.UnitBase = {
	__parents = {"UnitProperties", "UnitInventory", "StatusEffectObject", "ReactionObject" },
}
DefineReactionsPreset("Unit", "UnitBase", "unit_reactions", "MsgReactionsPreset") -- DefineClass.UnitReactionsPreset

function UnitBase:UnregisterReactions()
	for _, effect in ipairs(self.StatusEffects) do
		self:RemoveReactions(effect)
	end
	
	self:ForEachItem(false, function(item, slot, left, top, self)
		if slot ~= "SetpieceWeapon" then
			item:UnregisterReactions(self)
		end
	end, self)
end

function UnitBase:RegisterReactions()
	for _, effect in ipairs(self.StatusEffects) do
		self:AddReactions(effect, effect.unit_reactions)
	end
	
	self:ForEachItem(false, function(item, slot, left, top, self)
		if slot ~= "SetpieceWeapon" then
			item:RegisterReactions(self) -- will add reactions from item and components (in case of firearm with components)
		end
	end, self)
end

function OnMsg.MercHired(merc_id, price, days, alreadyHired)
	if not alreadyHired then
		gv_UnitData[merc_id]:RegisterReactions()
	end
end

function UnitBase:GetPersonalMorale()
	local teamMorale = self.team and self.team.morale or 0
	local personalMorale = 0
	
	--reduce morale for at least one disliked merc in team
	local isDisliking = false
	for _, dislikedMerc in ipairs(self.Dislikes) do
		local dislikedIndex = table.find(self.team.units, "session_id", dislikedMerc)
		if dislikedIndex and not self.team.units[dislikedIndex]:IsDead() then
			personalMorale = personalMorale - 1
			isDisliking = true
			break
		end
	end
	--increase morale for no disliked and at least one liked merc
	if not isDisliking then
		for _, likedMerc in ipairs(self.Likes) do
			local likedIndex = table.find(self.team.units, "session_id", likedMerc)
			if likedIndex and not self.team.units[likedIndex]:IsDead()  then
				personalMorale = personalMorale + 1
				break
			end
		end
	end
	--lower morale if below 50% or 3+ wounds (REVERT for psycho perk)
	local isWounded = false
	local idx = self:HasStatusEffect("Wounded")
	if idx and self.StatusEffects[idx].stacks >= 3 then
		isWounded = true
	end
	if self.HitPoints < MulDivRound(self.MaxHitPoints, 50, 100) or isWounded then
		if HasPerk(self, "Psycho") then
			personalMorale = personalMorale + 1
		else
			personalMorale = personalMorale - 1
		end
	end
	--lower morale if liked merc has died recently
	for _, likedMerc in ipairs(self.Likes) do
		local ud = gv_UnitData[likedMerc]
		if ud and ud.HireStatus == "Dead" then
			local deathDay = ud.HiredUntil
			if deathDay + 7 * const.Scale.day > Game.CampaignTime then
				personalMorale = personalMorale - 1
				break
			end
		end
	end
	
	personalMorale = self:CallReactions_Modify("OnCalcPersonalMorale", personalMorale)
	
	return Clamp(personalMorale + teamMorale, -3, 3)
end

DefineClass.Unit = {
	__parents = { "Movable", "CombatObject", "UnitBase",
		"GameDynamicSpawnObject", "AppearanceObject", "Interactable", "StepObject", "SyncObject", "ComponentSound",
		"SpawnFXObject", "HittableObject", "ComponentCustomData", "CombatTaskOwner", "AmbientLifeZoneUnit",
	},
	
	properties = {
		{category = "Ambient Life", id = "ViewPerpetual", editor = "buttons", default = false,
			no_edit = function(self) return not self.perpetual_marker end,
			buttons = {
				{ name = "View Perpetual Marker", func = function(self)
					ViewObject(self.perpetual_marker)
				end},
				{ name = "Select Perpetual Marker", func = function(self)
					editor.ClearSel()
					editor.AddObjToSel(self.perpetual_marker)
				end},
			},
		},
		{category = "Ambient Life", id = "ViewSpawner", editor = "buttons", default = false,
			no_edit = function(self) return not self.spawner end,
			buttons = {
				{ name = "View Spawner", func = function(self)
					ViewObject(self.spawner)
				end},
				{ name = "Select  Spawner", func = function(self)
					editor.ClearSel()
					editor.AddObjToSel(self.spawner)
				end},
			},
		},
		{category = "Ambient Life", id = "ViewRoutineSpawner", editor = "buttons", default = false,
			no_edit = function(self) return not self.routine_spawner end,
			buttons = {
				{ name = "View Routine Spawner", func = function(self)
					ViewObject(self.routine_spawner)
				end},
				{ name = "Select Routine Spawner", func = function(self)
					editor.ClearSel()
					editor.AddObjToSel(self.routine_spawner)
				end},
			},
		},
		-- hidden overridden properties
		{id = "animWeight"},
		{id = "animBlendTime"},
		{id = "anim2"},
		{id = "anim2BlendTime"},
	},
	
	flags = { efUnit = true, cofComponentColorizationMaterial = true, gofUnitLighting = true, gofOnRoof = false, gofAdjustZ = true },
	pfclass = 3,
	pfflags = const.pfmDestlockSmart + const.pfmCollisionAvoidance + const.pfmImpassableSource + const.pfmVoxelAligned + const.pfmOrient,
	pfclass_overwritten = false,
	ground_orient = false,
	anim_moments_single_thread = true,
	material_type = "Flesh",
	species = "Human",
	body_type = "Human",
	default_move_style = false,
	cur_move_style = false,
	cur_idle_style = false,
	move_step_fx = false,
	move_stop_anim_len = 0,
	move_stop_foot_left_anim = false,
	move_stop_foot_right_anim = false,

	-- Do not forget to add new class members to Get/SetDynamicData function to save in Game state (see GetCurrentGameVarValues)

	Appearance = false,
	-- reference to the corresponding UnitData in gv_UnitData[unit.session_id], all units (except setpiece testing clones) have this
	session_id = false,
	team = false,

	collision_radius = const.SlabSizeX/3,
	radius = const.SlabSizeX/4,

	stance = "Standing",
	unitdatadef_id = false, -- id in UnitDataDefs
	group = false, -- from UnitDataDefs[self.unitdatadef_id]
	target_dummy = false,
	cover_last_face_time = false,
	last_attack_session_id = false,
	current_weapon = "Handheld A",
	modify_animations_ar = false,

	aim_action_id = false,
	aim_action_params = false,
	aim_results = false,
	aim_attack_args = false,
	aim_fx_target = false,
	aim_fx_thread = false,
	aim_rotate_last_angle = false,
	aim_rotate_cooldown_time = false,
	action_visual_weapon = false,
	weapon_light_fx = false,

	return_pos = false,
	play_sequential_actions = false,
	command_specific_params = false,
	prepared_attack_obj = false,
	melee_threat_contour = false,
	prepared_bombard_zone = false,
	bombard_weapon = false,
	queued_action_id = false,
	queued_action_visual = false,
	queued_action_pos = false,

	is_melee_aim_last_turn = false,
	downing_action_start_time = false,

	last_turn_movement = false,
	last_turn_damaged = false,
	start_turn_pos = false,
	reposition_dest = false,
	reposition_path = false,
	reposition_marker = false,
	last_orientation_angle = false,
	last_attack_pos = false,

	god_mode = false,
	infinite_ammo = false,
	infinite_ap = false,
	infinite_dmg = false,
	infinite_condition = false,

	action_command = false,
	actions_nettravel = 0,  -- sent but not received yet
	ui_reserved_ap = 0,
	ui_override_ap = false, -- when set to something GetUIActionPoints will return this value to hide underlying AP shenanigans
	free_move_ap = 0,
	start_move_total_ap = 0,
	start_move_cost_ap = 0,
	start_move_free_ap = 0,

	combat_path = false,
	combat_path_obj = false,
	using_cumbersome = false, -- has any equipped Cumbersome items (cached, no need to save/load)
	attacked_this_turn = false,
	hit_this_turn = false,
	performed_action_this_turn = false,
	wounded_this_turn = false,
	downed_check_penalty = 0,

	ai_context = false,

	interruptable = true,
	interrupted = false,
	goto_interrupted = false,
	interrupt_callback = false,
	action_interrupt_callback = false,

	is_moving = false,
	goto_target = false,
	goto_stance = false,
	goto_hide = false,
	in_combat_movement = false,
	visibility_override = false,
	traverse_tunnel = false,
	tunnel_blockers = false,
	fallback_walk_speed = 3*guim, -- when the walk anim has no step
	perks_activated = false,
	attack_reason = false, -- additional prefix text to attack log entry (e.g. retaliation, overwatch, etc)
	opportunity_attack = false,
	effect_values = false, -- storage for status effect data/state
	enemy_visual_contact = false, -- does any enemy has visual contact with this unit
	alerted_by_enemy = false,
	last_known_enemy_pos = false, -- last location an enemy unit was seen
	marked_target_attack_args = false,
	
	pending_aware_state = false,
	pending_awareness_role = false,	 -- used for awareness visualization; not persisted
	suspicion = false,
	suspicious_body_seen = false,
	aware_reason = false,
	auto_face = true, -- the unit look at the nearest enemy
	reorientation_thread = false,
	setik_thread = false,

	spawner = false,  --NPC

	synced_anim = false,
	synced_anim_time = 0,
	synced_angle = 0,
	die_anim_prefix = false,
	on_die_attacker = false,
	on_die_hit_descr = false,
	death_explosion_played = false,
	death_fx_object = false,
	interacting_unit = false,
	killed_stance = false,

	combat_badge = false,
	ui_badge = false,
	ui_actions = false,
	combat_cache = false,
	villain_defeated = false,
	retreating = false,
	angle_before_interaction = false,
	highlight_reasons = false,

	banters = false,
	banters_played_lines = false,
	sequential_banter = false,
	approach_banters = false,
	approach_banters_distance = false,
	approach_banters_cooldown_id = false,
	last_played_banter_id = false, -- No need to serialize this
	
	visible = true,
	interactable_highlight_ctr = false,
	highlight_collection = false,
	
	-- general (out-of-combat) behaviors
	behavior = false, -- command to set
	behavior_params = false, -- parameters to set

	-- in-combat behaviors
	combat_behavior = false, -- command to set
	combat_behavior_params = false, -- parameters to set

	entrance_marker = false,

	neutral_ai_dont_move = false,
	neutral_retal_attacked = false,

	pain_thread = false,
	update_attached_weapons_thread = false,

	routine = "StandStill",
	routine_area = "self",
	routine_spawner = false,
	ephemeral = false,
	perpetual_marker = false,
	teleport_allowed_once = false,
	conflict_ignore = false,
	visit_command = false,
	visit_marker = false,
	visit_reached = false,
	cower_forbidden = false,
	cower_from = false,
	cower_angle = false,
	cower_cooldown = false,
	last_roam = false,
	last_visit = false,
	dead_markers_tried = false,
	mourn = false,
	maraud = false,
	enter_map_wait_time = false,
	enter_map_pos = false,
	seen_bodies = false,
	visit_test = false,
	carry_flare = false,
	infected = false,
	innerInfoRevealed = false, --used to mark the unit when revealed from the perk innerinfo

	fx_in_water = false,
	indoors = false,
	unarmed_weapon = false,
	warned_traps_pos = false,
	move_follow_target = false,
	move_follow_dest = false,
	move_attack_target = false,
	move_attack_action_id = false,
	move_attack_in_progress = false,
	waiting_attack = false,

	last_idle_aiming_time = false,

	place_wind_mod_trails = false,
	stain_update_times = false, -- async, visual, not saved

	__toluacode = empty_func,
	PrePlay = empty_func,
	PostPlay = empty_func,
	
	throw_died_message = false,
	is_despawned = false, -- Set briefly in Unit:Despawn before it is destroyed but after the sync with unitdata.
}

local function StoreBehaviorParamTbl(tbl)
	if not tbl then return end
	local stored, stored_handles
	for k, v in pairs(tbl) do
		if IsKindOf(v, "Object") then
			if not stored_handles then
				stored_handles = {}
				stored = stored or {}
				stored.__stored_obj_value = stored_handles
			end
			stored[k] = v.handle
			stored_handles[k] = true
		elseif type(v) == "table" then
			local new_value = StoreBehaviorParamTbl(v)
			if new_value ~= v then
				if not stored then
					stored = {}
				end
				stored[k] = new_value
			end
		end
	end
	if not stored then
		return tbl
	end
	-- copy the skipped values
	for k, v in pairs(tbl) do
		if stored[k] == nil then
			stored[k] = v
		end
	end
	return stored
end

local function RestoreBehaviorParamTbl(stored)
	if not stored then return end
	local stored_handles = stored.__stored_obj_value
	if stored_handles then
		stored.__stored_obj_value = nil
	end
	for k, v in pairs(stored) do
		if type(v) == "table" then
			RestoreBehaviorParamTbl(v)
		end
	end
	for k in pairs(stored_handles) do
		stored[k] = HandleToObject[ stored[k] ]
	end
end

function Unit:GetDynamicData(data)
	local class = g_Classes[self.class]
	data.session_id = self.session_id or nil
	data.unitdatadef_id = self.unitdatadef_id or nil
	data.ground_orient = self.ground_orient or nil
	data.stance  = self.stance ~= class.stance and self.stance or nil
	data.return_pos = self.return_pos or nil
	data.current_weapon = self.current_weapon ~= class.current_weapon and self.current_weapon or nil
	data.perks_activated = next(self.perks_activated) and self.perks_activated or nil
	data.Groups = #(self.Groups or "") > 0 and self.Groups or nil
	data.villain_defeated = self.villain_defeated or nil
	data.retreating = self.retreating or nil
	if self.command == "BanterIdle" then
		data.command = "Idle"
	end
	data.command_specific_params = next(self.command_specific_params) and self.command_specific_params or nil
	data.last_attack_session_id = self.last_attack_session_id or nil
	data.banters_played_lines = self.banters_played_lines or nil
	data.free_move_ap = self.free_move_ap ~= 0 and self.free_move_ap or nil
	data.neutral_ai_dont_move = self.neutral_ai_dont_move or nil
	data.enemy_visual_contact = self.enemy_visual_contact or nil
	if next(self.effect_values) then
		local effect_values = {}
		for k, v in pairs(self.effect_values) do
			effect_values[k] = v or nil
		end
		data.effect_values = next(effect_values) and effect_values or nil
	end
	data.is_melee_aim_last_turn = self.is_melee_aim_last_turn or nil
	data.performed_action_this_turn = self.performed_action_this_turn or nil
	data.carry_flare = self.carry_flare or nil

	for i, unit in ipairs(self.attacked_this_turn) do
		data.attacked_this_turn = data.attacked_this_turn or {}
		data.attacked_this_turn[i] = unit.handle
	end
	for i, unit in ipairs(self.hit_this_turn) do
		data.hit_this_turn = data.hit_this_turn or {}
		data.hit_this_turn[i] = unit.handle
	end
	for unit, _ in pairs(self.seen_bodies) do
		data.seen_bodies = data.seen_bodies or {}
		data.seen_bodies[unit:GetHandle()] = true
	end
	data.visit_test = self.visit_test or nil
	data.wounded_this_turn = self.wounded_this_turn or nil
	data.downed_check_penalty = self.downed_check_penalty ~= 0 and self.downed_check_penalty or nil
	data.last_known_enemy_pos = self.last_known_enemy_pos or nil
	data.last_turn_damaged = self.last_turn_damaged or nil

	if self.target_dummy then
		data.pos = self.target_dummy:GetPos()
		data.vpos = nil
		data.vpos_time = nil
	elseif self.traverse_tunnel then
		data.pos = self.traverse_tunnel.end_point
		data.vpos = nil
		data.vpos_time = nil
	end
	if self.behavior then
		data.behavior = self.behavior
		data.behavior_params = StoreBehaviorParamTbl(self.behavior_params)
		if data.behavior == "ExitMap" and data.behavior_params[2] then
			data.behavior_params[2] = Max(0, data.behavior_params[2] - GameTime())
		end
	end
	if self.combat_behavior then
		data.combat_behavior = self.combat_behavior
		data.combat_behavior_params = StoreBehaviorParamTbl(self.combat_behavior_params)
	end
	if self.marked_target_attack_args then
		data.marked_target_attack_args = StoreBehaviorParamTbl(self.marked_target_attack_args)
	end
	if self.spawner then
		data.spawner = self.spawner.handle
	end
	if IsValid(self.prepared_bombard_zone) then
		data.prepared_bombard_zone = self.prepared_bombard_zone.handle
	end

	if next(self.banters) then
		data.banters = self.banters
		data.sequential_banter = self.sequential_banter or nil
	end
	if next(self.approach_banters) then
		data.approach_banters = self.approach_banters
		data.approach_banters_distance = self.approach_banters_distance or nil
		data.approach_banters_cooldown_id = self.approach_banters_cooldown_id or nil
	end
	data.die_anim_prefix = self.die_anim_prefix or nil

	data.aware = self:IsAware() or nil
	data.pending_aware_state = self.pending_aware_state or nil
	data.suspicion = (self.suspicion or 0) > 0 and self.suspicion or nil
	data.suspicious_body_seen = self.suspicious_body_seen or nil
	if IsValid(self.alerted_by_enemy) then
		data.alerted_by_enemy = self.alerted_by_enemy.handle
	end

	data.routine = (self.routine ~= class.routine) and self.routine or nil
	data.routine_area = (self.routine_area ~= class.routine_area) and self.routine_area or nil
	data.routine_spawner = self.routine_spawner and self.routine_spawner.handle or nil
	data.zone = self.zone and self.zone.handle or nil
	data.ephemeral = self.ephemeral or nil
	data.perpetual_marker = self.perpetual_marker and self.perpetual_marker.handle or nil
	data.teleport_allowed_once = self.teleport_allowed_once or nil
	data.conflict_ignore =self.conflict_ignore or nil
	data.visit_command = self.visit_command or nil
	data.visit_reached = self.visit_reached or nil
	data.max_dead_slot_tiles = self.max_dead_slot_tiles or nil
	if self.visit_marker then
		data.visit_marker = self.visit_marker.handle
	end
	data.cower_forbidden = self.cower_forbidden or nil
	if self.cower_from then
		data.cower_from = self.cower_from
		data.cower_angle = self.cower_angle or nil
	end
	data.cower_cooldown = self.cower_cooldown or nil
	data.last_roam = self.last_roam and self.last_roam.handle or nil
	data.last_visit = self.last_visit and self.last_visit.handle or nil
	data.dead_markers_tried = self.dead_markers_tried or nil
	data.mourn = self.mourn and self.mourn.handle or nil
	data.maraud = self.maraud and self.maraud.handle or nil
	data.enter_map_wait_time = self.enter_map_wait_time and (self.enter_map_wait_time - GameTime()) or nil
	data.enter_map_pos = self.enter_map_pos or nil
	data.last_attack_pos = self.last_attack_pos or nil

	local unit_data = UnitDataDefs[self.unitdatadef_id]
	if self.Name ~= (unit_data and unit_data.Name) then
		data.Name = self.Name
	end
	data.default_move_style = self.default_move_style or nil
	data.cur_move_style = self.cur_move_style or nil
	data.cur_idle_style = self.cur_idle_style or nil
	data.on_die_hit_descr = self.on_die_hit_descr or nil
	data.death_explosion_played = self.death_explosion_played or nil
	data.infected = self.infected or nil
	data.innerInfoRevealed = self.innerInfoRevealed or nil
	data.throw_died_message = self.throw_died_message or nil
	data.lastFiringMode = self.lastFiringMode or nil
	data.queued_action_id = self.queued_action_id or nil
end

function Unit:SetDynamicData(data)
	self.session_id = data.session_id
	self.unitdatadef_id = data.unitdatadef_id or data.template_name
	self:UpdateFXClass()		-- IsMerc() depends on .unitdatadef_id, e.g. ImportantUnit

	self.spawner = HandleToObject[data.spawner]
	self.target_dummy = HandleToObject[data.target_dummy]

	-- these are needed to be restored before calling EnterMap command of AL
	self.zone = HandleToObject[data.zone] or false
	for _, group_name in ipairs(data.Groups) do
		self:AddToGroup(group_name)
	end
	self.enter_map_wait_time = data.enter_map_wait_time or false
	self.enter_map_pos = data.enter_map_pos or false
	self.last_attack_pos = data.last_attack_pos or false
	if data.combat_behavior then
		RestoreBehaviorParamTbl(data.combat_behavior_params)
		self:SetCombatBehavior(data.combat_behavior, data.combat_behavior_params)
	end
	if data.behavior then
		RestoreBehaviorParamTbl(data.behavior_params)
		if data.behavior == "OverwatchAction" or data.behavior == "PinDown" then
			self:SetCombatBehavior(data.behavior, data.behavior_params)
			self:SetBehavior(data.behavior, data.behavior_params)
		elseif data.behavior == "Dead" or data.behavior == "VillainDefeat" or data.behavior == "Hang" then
			self:SetCombatBehavior(data.behavior, data.behavior_params)
			self:SetBehavior(data.behavior, data.behavior_params)
		elseif data.behavior == "ExitMap" then
			if data.behavior_params[2] then
				data.behavior_params[2] = GameTime() + data.behavior_params[2]
			end
			self:SetBehavior(data.behavior, data.behavior_params)
		else
			self:SetBehavior(data.behavior, data.behavior_params)
		end
	end
	if data.marked_target_attack_args then
		self.marked_target_attack_args = RestoreBehaviorParamTbl(data.marked_target_attack_args)
	end
	 -- this needs to be after restoring self.spawner - long chain of invocations that ultimately results in a neutral unit
	if self.enter_map_wait_time and not IsKindOf(self.zone, "AmbientZoneMarker") then
		-- NOTE: old save with new map source for which unit's spawner zone has been deleted from the map
		DoneObject(self)
		return
	end
	self.last_roam = HandleToObject[data.last_roam] or false
	self.last_visit = HandleToObject[data.last_visit] or false
	self.perpetual_marker = HandleToObject[data.perpetual_marker] or false	-- needed to restore Visit cmd
	self.visit_reached = data.visit_reached or false
	self:FillMerc()

	self.stance = self.species ~= "Human" and "" or data.stance
	
	-- Weird save game compat
	if self.stance and type(self.stance) == "boolean" then
		self.stance = self.species ~= "Human" and "" or "Standing"
	end
	
	self.return_pos = data.return_pos
	self.current_weapon = data.current_weapon
	self.perks_activated = data.perks_activated or {}
	self.villain_defeated = data.villain_defeated
	self.retreating = data.retreating
	self.command_specific_params = data.command_specific_params
	self.last_attack_session_id = data.last_attack_session_id
	self.free_move_ap = data.free_move_ap
	self.neutral_ai_dont_move = data.neutral_ai_dont_move
	self.effect_values = table.copy(data.effect_values or data.effect_expirations) -- savegame compat support (effect_expirations)
	self.is_melee_aim_last_turn = data.is_melee_aim_last_turn or false
	self.enemy_visual_contact = data.enemy_visual_contact
	self.suspicion = data.suspicion
	self.suspicious_body_seen = data.suspicious_body_seen
	self.pending_aware_state = data.pending_aware_state
	if self.pending_aware_state == "reposition" then
		self.pending_aware_state = nil
	end
	self.max_dead_slot_tiles = data.max_dead_slot_tiles or false
	if data.aware then
		self:RemoveStatusEffect("Unaware")
		self:RemoveStatusEffect("Suspicious")
	end
	self.alerted_by_enemy = HandleToObject[data.alerted_by_enemy]
	self.last_known_enemy_pos = data.last_known_enemy_pos
	self.last_turn_damaged = data.last_turn_damaged
	self.performed_action_this_turn = data.performed_action_this_turn
	if data.carry_flare then
		self:RoamAttachFlare()
	end

	self.attacked_this_turn = {}
	for i, handle in ipairs(data.attacked_this_turn) do
		self.attacked_this_turn[i] = HandleToObject[handle]
	end
	self.hit_this_turn = {}
	for i, handle in ipairs(data.hit_this_turn) do
		self.hit_this_turn[i] = HandleToObject[handle]
	end
	self.seen_bodies = {}
	for handle, _ in pairs(data.seen_bodies) do
		local unit = HandleToObject[handle] or false
		self.seen_bodies[unit] = true
	end
	self.visit_test = data.visit_test or false
	self.wounded_this_turn = data.wounded_this_turn
	self.downed_check_penalty = data.downed_check_penalty	
	
	if data.prepared_bombard_zone then
		self.prepared_bombard_zone = HandleToObject[data.prepared_bombard_zone]
	end

	self.die_anim_prefix = data.die_anim_prefix
	self:UpdateMoveAnim()
	self:OnGearChanged("isLoad")

	-- shuffle looping animations
	if self:IsAnimLooping(1) then
		local phase = self:Random(GetAnimDuration(self:GetEntity(), self:GetAnim(1)))
		self:SetAnimPhase(1, phase)
	end

	self.banters = data.banters
	self.sequential_banter = data.sequential_banter or false
	self.banters_played_lines = data.banters_played_lines or false
	self.approach_banters = data.approach_banters
	self.approach_banters_distance = data.approach_banters_distance
	self.approach_banters_cooldown_id = data.approach_banters_cooldown_id

	self.routine = data.routine or "StandStill"
	self.routine_area = data.routine_area or "self"
	self.routine_spawner = HandleToObject[data.routine_spawner] or false
	self.ephemeral = data.ephemeral or false
	self.teleport_allowed_once = data.teleport_allowed_once or false
	self.conflict_ignore = data.conflict_ignore or false
	self.visit_command = data.visit_command or false
	self.visit_marker = HandleToObject[data.visit_marker] or false
	self.cower_forbidden = data.cower_forbidden or false
	self.cower_from = data.cower_from or false
	self.cower_angle = data.cower_angle or false
	self.cower_cooldown = data.cower_cooldown or false
	self.dead_markers_tried = data.dead_markers_tried or false
	self.mourn = HandleToObject[data.mourn] or false
	self.maraud = HandleToObject[data.maraud] or false

	if data.Name then
		self.Name = data.Name
	end
	if data.ground_orient then
		self:SetFootPlant(true, 0)
	else
		self:SetAxis(axis_z)
	end
	self.default_move_style = data.default_move_style or false
	self.cur_move_style = data.cur_move_style or false
	self.cur_idle_style = data.cur_idle_style or false
	self.on_die_hit_descr = data.on_die_hit_descr or false
	if data.death_explosion_played then
		self.death_explosion_played = data.death_explosion_played
		self:PlaceDeathFXObject(true)
	end
	self.infected = data.infected or false
	self.innerInfoRevealed = data.innerInfoRevealed or false
	if self.command == "Idle" and self:IsValidPos() then
		local x, y, z = GetPassSlabXYZ(self)
		if not x or not CanDestlock(self, x, y, z) then
			local has_path, pos = pf.HasPosPath(self, self)
			if pos then
				self:SetPos(GetPassSlab(pos))
			end
		end
	end
	
	self.throw_died_message = data.throw_died_message or false
	self.lastFiringMode = data.lastFiringMode or false
	self.queued_action_id = data.queued_action_id or false

	if data.spawner and not self.spawner then
		self:SetCommand("Despawn") -- the spawner is not present in the new map version
	end
end

function OnMsg.UnitCreated(self)
	if self.unitdatadef_id and next(UnitDataDefs[self.unitdatadef_id].AdditionalGroups) then
		self:AddAdditionalGroups()
	end
end

function Unit:SetQueuedAction(id)
	self.queued_action_id = id or false
	if self.ui_badge then
		self.ui_badge:UpdateEnemyVisibility()
	end
	if not self.queued_action_id then
		if IsValid(self.queued_action_visual) then
			DoneObject(self.queued_action_visual)
			self.queued_action_visual = false
		end
		self.queued_action_pos = false
	end	
end

function Unit:AddAdditionalGroups()
	if next(self.additional_groups) then 
		for _, group in ipairs(self.additional_groups) do
			self:AddToGroup(group)
		end
	else
		self.additional_groups = {}
		local exclusiveTable = {}
		for _, group in ipairs(UnitDataDefs[self.unitdatadef_id].AdditionalGroups) do
			if group.Exclusive then
				table.insert(exclusiveTable, {Name = group.Name, Weight = group.Weight})
			else
				local roll = InteractionRand(100, "BanterGroup")
				if roll < group.Weight then
					self:AddToGroup(group.Name) 
					table.insert(self.additional_groups, group.Name)
				end
			end
		end
		
		if next(exclusiveTable) then
			local exclusiveGroup = table.weighted_rand(exclusiveTable, "Weight", InteractionRand(1000000, "BanterGroup"))
			self:AddToGroup(exclusiveGroup.Name)
			table.insert(self.additional_groups, exclusiveGroup.Name)
		end
	end
end

function Unit:Init()
	-- copy base values from material def
	if self.unitdatadef_id then
		self:AddToGroup(self.unitdatadef_id)
	end
	if not self.command_specific_params then
		self.command_specific_params = {}
		if self.spawner then
			local params = {
				weapon_anim_prefix = not self.spawner.use_weapons and "civ_" or nil,
			}
			params.idle_stance = self.spawner.idle_stance ~= g_StanceActionDefault and self.spawner.idle_stance or nil
			params.idle_action = self.spawner.idle_action ~= g_StanceActionDefault and self.spawner.idle_action or nil
			self:SetCommandParams("Idle", params)
			self:SetCommandParams("Visit", params)
			self:SetCommandParams("Roam", params)
			self:SetCommandParams("RoamSingle", params)
		end
	end
	if self.session_id then
		self:InitMerc()
		self:UpdateOutfit()
		self.retreating = nil -- spawning anew resets this status
		if self.villain then
			self:AddToGroup("Villains")
		end
	end
	self.perks_activated = {}
	self.seen_bodies = {}
	self.stain_update_times = {}
	self.AIKeywords = table.copy(self.AIKeywords)
	if IsMerc(self) then
		self.fx_actor_class = "ImportantUnit"
	end
	Msg("UnitCreated", self)
end

function Unit:InitFromMaterialPreset(preset)
end

function Unit:Done()
	self:TunnelsUnblock()
	self:RemoveALDeadMarkers()
	if self.team then
		table.remove_value(self.team.units, self)
		if not self.team.neutral then
			for team, list in pairs(g_RevealedUnits) do
				table.remove_value(list, self)
			end
		end
	end
	table.remove_value(g_Units, self)
	if self.session_id and g_Units[self.session_id] == self then
		g_Units[self.session_id] = nil
	end
	if self.unarmed_weapon then
		self.unarmed_weapon = nil
	end
	if self.bombard_weapon then
		DoneObject(self.bombard_weapon)
	end
	SelectionRemove(self)
	SetCombatActionState(self, nil)
	DeleteBadgesFromTarget(self)
	DeleteThread(self.pain_thread)
	DeleteThread(self.update_attached_weapons_thread)
	DeleteThread(self.setik_thread)
	if self:IsSyncObject() then
		Msg("UnitDespawned", self)
	end
	self:FreeVisitable()
	if self.perpetual_marker then
		self.perpetual_marker.perpetual_unit = false
	end
	self:SetTargetDummy(false)
	InvalidateUnitLOS(self)
	local idx = g_AIExecutionController and next(g_AIExecutionController.group_to_follow) and table.find(g_AIExecutionController.group_to_follow, "session_id", self.session_id)
	if idx then
		table.remove(g_AIExecutionController.group_to_follow, idx)
	end
end

function Unit:SetBehavior(behavior, params)
	self.behavior = behavior
	self.behavior_params = params
	
	if self.carry_flare and behavior and behavior ~= "Roam" and behavior ~= "RoamSingle" then
		self:RoamDropFlare()
	end
end

function Unit:SetCombatBehavior(behavior, params)
	self.combat_behavior = behavior
	self.combat_behavior_params = params
end

function Unit:ClearBehaviors(behavior)
	if self.behavior == behavior then
		self:SetBehavior()
	end
	if self.combat_behavior == behavior then
		self:SetCombatBehavior()
	end
end

function CopyPropertiesShallow(to,source, properties, copy_values)
	assert(IsKindOf(to, "Modifiable") and IsKindOf(source, "Modifiable"))
	local mods = source.modifications or empty_table
	for i = 1, #properties do
		local prop = properties[i]
		if prop_eval(prop.dont_save, source, prop) then goto continue end
		
			local prop_id = prop.id
			if prop.modifiable then
				to:SetBase(prop_id, source["base_" .. prop_id])
			else
				local value = source:GetProperty(prop_id)
				local source_value_is_dest_default = value == nil or value == to:GetDefaultPropertyValue(prop_id, prop)
				local to_value = to:GetProperty(prop_id)
				local dest_value_is_default = to_value == nil or to_value == value
				local is_default = source_value_is_dest_default and dest_value_is_default
				if is_default then goto continue end
				
				if copy_values and type(to_value) == "table" then
					table.clear(to_value)
					local copy = table.copy(value)
					for key, val in pairs(copy) do
						if IsKindOf(val, "PropertyObject") then
							to_value[key] = val:Clone()
						else
							to_value[key] = val
						end
					end
				else
					to:SetProperty(prop_id, value)
				end
			end
		
		::continue::
	end
end

function Unit:InitMerc()
	g_UnarmedWeapon = g_UnarmedWeapon or PlaceInventoryItem("Unarmed")
	local unitData = gv_UnitData[self.session_id]
	
	if unitData.species ~= "Human" then
		self.stance = ""
	end
	self.fallback_body = unitData.gender or self.fallback_body

	self:SyncWithSession("session")

	self:InitMercWeaponsAndActions()
	self:OnGearChanged()

	ObjModified(self)
end

function Unit:InitMercWeaponsAndActions()
	self:ReloadAllEquipedWeapons()
	self:RecalcUIActions()
self:SetCommand("Idle")
end

function Unit:GetSide(reset_teams)
	local side = not reset_teams and self.team and self.team.side or false
	
	-- If the unit is not a part of any team, decide his team based on his campaign side.
	assert(self.session_id) -- all units should be represented in gv_UnitData
	local unit_data = self.session_id and gv_UnitData[self.session_id]

	if unit_data then 
		if unit_data.Squad and gv_Squads[unit_data.Squad] then
			side = side or gv_Squads[unit_data.Squad].Side
		elseif unit_data.CurrentSide ~= "" then 
			-- The unit could've changed sides
			side = side or unit_data.CurrentSide
		end
	end
		
	if not side and self.spawner then
		side = self.spawner.Side
	end

	-- Ephemeral units
	side = side or "neutral"
	
	return side
end

function Unit:FillMerc()
	local ud = gv_UnitData[self.session_id]
	if ud then ud:StatusEffectsCleanUp() end
	self:SyncWithSession("session")
	
	self:UpdateOutfit()
	self:OnGearChanged("isLoad")
	CombatPathReset(self)
	self:UpdateStatusEffectIndex()
	self:UpdateSignatureRecharges()
	
	if self.enter_map_wait_time then
		self.zone:InitUnit(self)
		self:SetCommand("EnterMap", self.zone, self.enter_map_pos, self.enter_map_wait_time)
	elseif self.behavior == "Hang" then
		self:SetCommand("Hang")
	elseif self.behavior == "Visit" then
		local marker = self.behavior_params[1] and self.behavior_params[1][1]
		if marker then
			local new_visitable = marker:GetVisitable()
			new_visitable.reserved = self.handle
			self.behavior_params[1] = new_visitable
			if marker.tool_attached then
				-- Tool is not a permanent object so it needs to be respawned
				if IsKindOf(marker, "AL_Carry") then
					self:SetState(marker.VisitIdle)
				end
				marker:SpawnTool(self)
			end
			if not (marker and marker:CanVisit(self, "for perpetual")) then
				self:ResetAmbientLife()
			elseif self.visit_reached then	-- walking to the marker can fail do to PF issues
				self:SetCommand("Visit", new_visitable, self.perpetual_marker)
			elseif IsKindOf(marker, "AL_Carry") then
				self:SetCommand("Visit", new_visitable, marker, "already in perpetual")
			else
				self:SetBehavior()
				self:SetCommand("Idle")
			end
		else
			-- persisted marker is deleted from the map
			self:SetBehavior()
			self:SetCommand("Idle")
		end
	else
		assert(self:IsValidPos())
		if self:IsValidPos() then
			self:SetCommand("Idle")
		end
	end
	ObjModified(self)
end

function Unit:SyncWithSession(source) -- sync map objects with session data
	if not self.session_id then -- early out for setpiece testing, done with Unit clones with no session_id
		return
	end
	local unit_data = self.session_id and gv_UnitData[self.session_id]
	if not unit_data then
		assert(false, string.format("All units should have corresponding unit data: session_id (%s), template name (%s)", self.session_id or "", self.unitdatadef_id or ""))
		return
	end
	
	local from, to
	if source == "map" then
		from = self
		to = unit_data
	elseif source == "session" then
		from = unit_data
		to = self
	end
	 -- we need to remove reaction handlers and then apply them anew, as this can potentially change the list of status effect in the target object
	to:UnregisterReactions()
	CopyPropertiesShallow(to, from, UnitProperties:GetProperties())
	CopyPropertiesShallow(to, from, UnitInventory:GetProperties())
	 
	 -- StatusEffects table reference shouldn't be changed as it is observed by various UI at any given point.	 
	CopyPropertiesShallow(to, from, StatusEffectObject:GetProperties(), "copy_values")
	to:RegisterReactions()
	
	to:ApplyModifiersList(self.applied_modifiers)
	if source == "session" then
		to:OnSetActiveWeapon()
		to.AIKeywords = table.copy(to.AIKeywords)
	end	
	if (not g_Combat and self.behavior == "Dead") or (g_Combat and self.combat_behavior == "Dead") then
		self.HitPoints = 0
	end
	
	ObjModified(from)
	ObjModified(to)
	ObjModified(to.StatusEffects)
	ObjModified(from.StatusEffects)
end

function NetSyncEvents.SyncUnitProperties(source)
	SyncUnitProperties(source)
end

function SyncUnitProperties(source)
	if not GameState.entered_sector then return end
	
	for _, unit in ipairs(g_Units) do
		unit:SyncWithSession(source)
	end
	Msg("UnitPropertiesSynced")
end

function OnMsg.LoadSessionData()
	SyncUnitProperties("session")
	-- apply modifiers on load for units that are not on current map and have no g_Unit 
	--(syncwith session apply the modifiers for g_Units)
	for session_id, unit in pairs(gv_UnitData) do
		if not g_Units[session_id] then
			unit:ApplyModifiersList(unit.applied_modifiers)
			if unit.HireStatus and unit.HireStatus == "Hired" then
				unit:RegisterReactions()
			end
		end	
	end	
end

function OnMsg.GatherSessionData()
	if not gv_SatelliteView then -- in satellite view units session data is updated
		SyncUnitProperties("map")
	end
end

local function restore_default_props(unit, data, properties)
	for id, prop in ipairs(properties) do
		local id = prop.id
		local editor = prop_eval(prop.editor, unit, prop)
		if editor and not prop_eval(prop.dont_save, unit, prop) then
			local value, default = unit:GetProperty(id), data:GetProperty(id)
			if value ~= default and (type(value) == "function" or type(value) == "table" and data:IsDefaultPropertyValue(id, prop, value)) then
				unit:SetProperty(id, default)
			end
		end
	end
end

-- On Lua reload, put the defaults from UnitData classes back into Unit instances
-- (important for function values, so they don't get saved)
function OnMsg.Autorun()
	for _, unit in ipairs(g_Units) do
		local unit_data = unit.session_id and gv_UnitData[unit.session_id]
		if unit_data then
			restore_default_props(unit, unit_data, UnitProperties:GetProperties())
		end
	end
end

function Unit:GetSatelliteSquad()
	local squad
	if self:IsDead() then
		squad = self.Squad
	else
		local unitData = gv_UnitData[self.session_id]
		squad = unitData and unitData.Squad
	end
	return gv_Squads and gv_Squads[squad] or false
end

function Unit:GameInit()
	local side = self.team and self.team.side	
	if CheatEnabled("GodMode", side) then
		self:GodMode("god_mode", true)
	end
	if CheatEnabled("InfiniteAP", side) then
		self:GodMode("infinite_ap", true)
	end
	if CheatEnabled("OneHpEnemies") and (side == "enemy1" or side == "enemy2") then
		self.HitPoints = 1
	end
	if self:HasStatusEffect("ManningEmplacement") then
		local handle = self:GetEffectValue("hmg_emplacement")
		local obj = HandleToObject[handle]
		if obj then
			self:EnterEmplacement(obj, true) -- instant take the right position
		end
	end
	self:UpdateBandageConsistency()
	
	self:SetContourOuterOccludeRecursive(true)
	self:UpdateGroundOrientParams()
	if not self:IsDead() then
		self:SetTargetDummyFromPos()
	end
end

function Unit:GetSyncedAnim()
	if self.synced_anim then
		return self.synced_anim, GameTime() - self.synced_anim_time
	end
	return self:GetStateText(), self:GetAnimPhase()
end

function Unit:GetStaticSpotPos(spot)
	local obj = self.target_dummy or self
	if type(spot) == "string" then
		local first, last = obj:GetSpotRange(obj:GetAnim(), spot)
		if first < 0 or last < 0 then
			return obj:GetRelativePoint(0, 0, guim)
		end
		spot = first
	end
	return obj:GetSpotLocPos(obj:GetAnim(), obj:GetAnimPhase(), spot)
end

function Unit:TriggerAction(cmd, ...)
	--[[if not g_Combat and cmd == "ChangeStance" then
		return self:InterruptCommand(cmd, ...)
	end--]]
	self:QueueCommand(cmd, ...)
end

function Unit:ReviveOnHealth(hp)
	self.HitPoints = hp or self.MaxHitPoints
	self:RemoveStatusEffect("Bleeding")
	self:NetUpdateHash("Revive", self.HitPoints)
	self:ClearHierarchyGameFlags(const.gofOnRoof)
	if self.behavior == "Dead" or self.behavior == "VillainDefeat" then
		self:SetBehavior()
		self:SetCombatBehavior()
	end
	InvalidateDiplomacy()
	self:FlushCombatCache()
	ObjModified(self)
end

function Unit:DropLoot(container)
	local is_npc = self:IsNPC() -- not a merc
	
	local debugText =  _InternalTranslate(self.Name) .. " dropping loot: (roll must be lower)"
	
	-- Locked items never drop.
	-- Go over the equipped items, drop them to "Inventory" based on their drop chance,
	-- Equipped items from Mercs always drop(except locked items). Otherwise check the drop chance.
	local droped_items = 0
	self:ForEachItem(function(item, slot_name, left, top, self, container, is_npc)
		if slot_name == "InventoryDead" then return end
		self:RemoveItem(slot_name, item)	
		
		local dropped
		local roll = self:Random(100)
		local slot = container and "Inventory" or "InventoryDead"
		
		debugText = debugText .. "\n " ..  _InternalTranslate(item.DisplayName) .. ": roll " .. roll .. "/" .. item.drop_chance .. "% chance" 

		if not item.locked and (not is_npc or roll < item.drop_chance) then
			if IsGameRuleActive("AmmoScarcity") and is_npc and IsKindOf(item, "InventoryStack") and IsKindOfClasses(item,{"Ammo", "Ordnance", "Grenade", "ThrowableTrapItem", "Flare"}) then
				local percent = GameRuleDefs.AmmoScarcity:ResolveValue("LootDecrease")
				item.Amount =  Max(1,item.Amount - MulDivRound(item.Amount, percent, 100))
			end	
			
			local addTo = container or self
			
			local pos, err = addTo:CanAddItem(slot, item)
			assert(pos, "Couldn't FIND pos in Inventory to place dropped item. Err: '" .. err .. "'")
			if pos then
				dropped, err = addTo:AddItem(slot, item, point_unpack(pos))
				assert(dropped, "Couldn't PLACE dropped item in Inventory. Err: '" .. err .. "'")
			end			
		end
		
		if not dropped then
			DoneObject(item)
		elseif slot == "InventoryDead" then
			droped_items = droped_items + (item:IsLargeItem() and 2 or 1)
		end
	end, self, container, is_npc)

	if droped_items > 0 then
		self.max_dead_slot_tiles = droped_items
	end

	CombatLog("debug", debugText)
end

function OnMsg.UnitDiedOnSector(unit, sector_id)
	local sector = gv_Sectors[sector_id]
	sector.dead_units = sector.dead_units or {}
	table.insert(sector.dead_units, unit.session_id)  
end

function Unit:DropAllItemsInAContainer(fall_pos)
	if not self:GetItem() then return end
	local container = GetDropContainer(self,fall_pos)
	self:ForEachItem(function(item, slot)
		self:RemoveItem(slot, item)
		
		if not container:AddItem("Inventory", item) then
			-- Fallback for too many items
			container = PlaceObject("ItemDropContainer")
			local drop_pos = terrain.FindPassable(container, 0, const.SlabSizeX/2)
			container:SetPos(drop_pos or self:GetPos())
			container:SetAngle(container:Random(360*60))
			container:AddItem("Inventory", item)
		end
	end)
		
	return container
end

function Unit:ShouldGetDowned(hit_descr)
	if not self:IsMerc() or not self.team or not self.team.player_team or (hit_descr and hit_descr.was_downed) then 
		return false 
	end
	if self.team and self.team:IsDefeated() then
		return false
	end
	if IsGameRuleActive("LethalWeapons") then
		return false
	end
	if IsGameRuleActive("ForgivingMode") then
		return true
	end
	if hit_descr then
		local value = GameDifficulties[Game.game_difficulty]:ResolveValue("InstantDeathHp") or -50
		if hit_descr.prev_hit_points - hit_descr.raw_damage <= value then
			return false
		end
	end
	if g_Combat then
		return not self:IsDowned()
	end
	return hit_descr and hit_descr.prev_hit_points > 1
end

function Unit:OnDie(attacker, hit_descr)
	CombatActionInterruped(self)
	RemoveFloatingTextsFrom(self, "DamageFloatingText")
	self.on_die_attacker = IsKindOf(attacker, "Trap") and attacker.attacker or attacker
	self.on_die_hit_descr = table.copy(hit_descr)
	self.on_die_hit_descr.armor_decay = nil
	self.on_die_hit_descr.armor_pen = nil
	
	if self:ShouldGetDowned(hit_descr) then
		hit_descr.explosion_fly = nil -- never do this when downing
		self.HitPoints = 1 -- make sure the unit is not considered dead and evicted from the UI
		local value = GameDifficulties[Game.game_difficulty]:ResolveValue("DownedTempHp") or 30
		if g_Combat then self:ApplyTempHitPoints(value) end
		--count downed units for tacticalsituation vr
		if attacker and IsKindOf(attacker, "Unit") and attacker.team.side ~= self.team.side then
			self.team.tactical_situations_vr.downedUnits = self.team.tactical_situations_vr.downedUnits and self.team.tactical_situations_vr.downedUnits 
			attacker.team.tactical_situations_vr.downedUnitsByTeam = attacker.team.tactical_situations_vr.downedUnitsByTeam and attacker.team.tactical_situations_vr.downedUnitsByTeam + 1 or 1
			PlayVoiceResponseTacticalSituation(table.find(g_Teams, attacker.team), "now")
		end
		self:SetCommand("GetDowned")
	else
		--printf("%s dies", _InternalTranslate(self.Name or ""))
		self.on_die_hit_descr = self.on_die_hit_descr or {}
		 -- Roam is considered visiting but doesn't have a last_visit
		 if self:IsVisiting() and self.last_visit and self.visit_reached then
			self.on_die_hit_descr.die_pos = self.last_visit:GetPos()
		end
		if string.match(self.session_id, "ClonedFootballPartner") then
			self.SetCommand = Unit.SetCommand
			self.zone.player_killed = true
		end
		if IsKindOf(self.last_visit, "AL_Football") then
			self.last_visit.player_killed = true
		end
		self:SetCommand("Die")
	end
end

function Unit:SetTired(value)
	UnitProperties.SetTired(self, value)
	
	if value==3 then
		self:SetCommand("GetDowned", "tired")	
	end
end

function Unit:IsGettingDowned()
	return self.command == "GetDowned"
end

function Unit:IsDowned()
	return self.command == "Downed" or self.combat_behavior == "Downed"
end

function Unit:IsIncapacitated()
	return self:IsDead() or self:IsDowned() or self:IsGettingDowned() or self.command == "Die"
end

function Unit:CanPassThroughInCombat()
	return self:GetEnumFlags(const.efResting) == 0 or self:IsDowned()
end

function Unit:CanContinueCombat()
	local isDead = self.command == "Die" or self:IsDead()
	local isDowned = self:IsDowned()
	local isTempUncontrollable = (self:HasStatusEffect("Unconscious") or self:HasStatusEffect("Stabilized")) and (not self:HasStatusEffect("Downed") or not self:HasStatusEffect("BleedingOut"))
	return not isDead and (not isDowned or isTempUncontrollable)
end

MapVar("g_NextUnitThread", false)
MapVar("g_LastUnitToShoot", false)

function Unit:GetDowned(tired, skip_anim)
	if not tired then
		self.HitPoints = 1 -- restore hp so Downed can be applied
		--printf("%s is downed", _InternalTranslate(self.Name or ""))
	end
	self.ActionPoints = 0
	self.stance = self:GetValidStance("Prone")
	self:InterruptPreparedAttack()
	self:RemovePreparedAttackVisuals()
	self:RemoveEnemyPindown()
	self:AlignOnDeath()
	self:RemoveStatusEffect("FreeMove")
	self:RemoveStatusEffect("Bleeding")
	self:RemoveStatusEffect("BandageInCombat")
	self:RemoveStatusEffect("StationedMachineGun")
	self:AddWounds(1)
	
	CombatActionInterruped(self)
	ObjModified(self)
	self:ClearPath()
	self:SetTargetDummyFromPos()
	if not tired then
		PlayVoiceResponse(self, "Downed")
	end
	SetCombatActionState(self, nil)

	local dlg = GetInGameInterfaceModeDlg()
	if IsKindOf(dlg, "IModeCommonUnitControl") and Selection and table.find(Selection, self) then
		dlg:NextUnit()
	end

	if IsMerc(self) then
		PlayFX("MercDowned", "start")
	end

	self.combat_behavior = "GetDowned"
	CheckGameOver()
	local base_idle = self:TryGetActionAnim("Idle", "Downed")
	if not (base_idle and IsAnimVariant(self:GetStateText(), base_idle)) then
		local pos = self:GetPos()
		if ShouldDoDestructionPass() then
			WaitMsg("DestructionPassDone", 1000) --wait for destro if slabs beneath us get destroyed, so we can get a falldown point
		end
		local x, y, z = FindFallDownPos(pos)
		if x and not pos:Equal(x, y, z) then
			self:FallDown(point(x, y, z))
			pos = self:GetPos()
		end
		local angle = self:GetOrientationAngle()
		self:SetPos(pos)
		if not skip_anim then
			local base_anim = self:GetActionBaseAnim("Downed", self.stance)
			local anim = self:GetStateText()
			if IsAnimVariant(anim, base_anim) then
				Sleep(self:TimeToAnimEnd())
			else
				anim = self:GetNearbyUniqueRandomAnim(base_anim)
				self:MovePlayAnim(anim, pos, pos, 0, nil, true, angle)
			end
		end
		if base_idle then
			if not IsAnimVariant(self:GetStateText(), base_idle) then
				local anim = self:GetNearbyUniqueRandomAnim(base_idle)
				self:SetState(anim)
			end
		else
			-- missing downed idle animation support
			local base_anim = self:GetActionBaseAnim("Downed", self.stance)
			local anim = self:GetStateText()
			if not IsAnimVariant(anim, base_anim) then
				anim = self:GetNearbyUniqueRandomAnim(base_anim)
			end
			local duration = GetAnimDuration(self:GetEntity(), anim)
			self:SetState(anim, 0, 0)
			self:SetAnimPhase(1, duration - 1)
		end
		self:SetGroundOrientation(angle, 0)
	end
	self.combat_behavior = false

	if not g_Combat and not self:IsDead() then
		Sleep(5000)
		self:SetCommand("DownedRally")
		return
	end
	if g_Combat and self == SelectedObj and not IsValidThread(g_NextUnitThread) then
		g_NextUnitThread = CreateMapRealTimeThread(function()
			-- Somebody could be panicking, during which units cannot be controlled.
			while g_AIExecutionController do
				WaitMsg("ExecutionControllerDeactivate", 50)
			end
			-- If the last unit is killed combat will be ended.
			if g_Combat then g_Combat:NextUnit(nil, "force") end
		end)
	end
	self.return_pos = nil

	if tired then
		self:AddStatusEffect("Unconscious")
	else
		MoraleModifierEvent("UnitDowned", self)
		self:AddStatusEffect("Downed")
	end
end

function Unit:Downed()
	Msg("UnitDowned", self)
	local base_idle = self:TryGetActionAnim("Idle", "Downed")
	if base_idle then
		if not IsAnimVariant(self:GetStateText(), base_idle) then
			local anim = self:GetNearbyUniqueRandomAnim(base_idle)
			self:SetState(anim)
			if GameState.sync_loading then
				self:SetAnimPhase(1, GetAnimDuration(self:GetEntity(), anim) - 1)
			end
		end
	else
		-- missing downed idle animation support
		local base_anim = self:GetActionBaseAnim("Downed", self.stance)
		local anim = self:GetStateText()
		if not IsAnimVariant(anim, base_anim) then
			anim = self:GetNearbyUniqueRandomAnim(base_anim)
		end
		local duration = GetAnimDuration(self:GetEntity(), anim)
		self:SetState(anim, 0, 0)
		self:SetAnimPhase(1, duration - 1)
	end
	self:SetFootPlant(true, 0)
	self:SetCombatBehavior("Downed")
	local target_dummy_phase = GetAnimDuration(self:GetEntity(), self:GetState())
	self:SetTargetDummy(nil, nil, nil, target_dummy_phase) -- current position, animation phase 0
	Halt()
end

local HeadshotHideParts = { "Head", "Hat", "Hat2", "Hair" }

function Unit:SetHeadshot(value)
	self.Headshot = value
	if not self.parts or self.species ~= "Human" then
		return
	end
	for i, name in ipairs(HeadshotHideParts) do
		local part = self.parts[name]
		if part then
			if value then
				part:ClearEnumFlags(const.efVisible)
			else
				part:SetEnumFlags(const.efVisible)
			end
		end
	end
	if value then
		local headshot_entity
		if self.gender == "Male" then
			headshot_entity = "FX_HeadMale_Headshot"
		elseif self.gender == "Female" then
			headshot_entity = "FX_HeadFemale_Headshot"
		end
		if headshot_entity then
			local part = PlaceObject("AppearanceObjectPart")
			if self:GetGameFlags(const.gofRealTimeAnim) ~= 0 then
				part:SetGameFlags(const.gofRealTimeAnim)
			end
			part:ChangeEntity(headshot_entity)
			self:Attach(part, self.parts.Head:GetAttachSpot())
			self.parts.Headshot = part
		end
	else
		DoneObject(self.parts.Headshot)
		self.parts.Headshot = nil
	end
end

function Unit:AlignOnDeath(dont_snap)
	local pos = self:GetVoxelSnapPos()
	if pos and self:GetDist(pos) > 0 and (not (self.on_die_hit_descr and self.on_die_hit_descr.die_pos)) then
		if not dont_snap then
			self:SetPos(pos)
		end
		-- make sure the unit dies on place in this case
		self.on_die_attacker = nil
		self.on_die_hit_descr = nil
	end
end

function Unit:Die(skip_anim)
	local attacker = self.on_die_attacker
	local hit_descr = self.on_die_hit_descr or {}
	local target_spot_group = hit_descr.spot_group
	local headshot = target_spot_group == "Head"
	local attack_action_id = attacker and CombatActions_LastStartedAction and CombatActions_LastStartedAction.unit == attacker and CombatActions_LastStartedAction.action_id
	local zoom_in = (self:IsLocalPlayerControlled() or headshot or attack_action_id == "KnifeThrow") and attacker and CurrentActionCamera and CurrentActionCamera[1] ~= self and CurrentActionCamera[2] == self and not self.villain
	local results = {}

	self:AlignOnDeath("don't snap in voxel")
	self:RoamDropFlare()

	if not skip_anim then
		if zoom_in then
			ZoomActionCamera()
		end

		-- Action camera should wait for this to be over before closing.
		if CurrentActionCamera then
			CurrentActionCamera.wait_signal = true
		end
	end
	
	if self.reincarnate then
		self:PlayDying()
		self:ReviveOnHealth()
		self:SetBehavior()
		self:SetCombatBehavior()
		self:SetCommand("Idle")
		return
	elseif self.immortal then
		self:ReviveOnHealth()
		self:AddStatusEffect("Unconscious")
		return
	end
	
	self.throw_died_message = "all"
	self.HitPoints = 0 -- needs to be before RemoveAllStatusEffects so that Wounded can detect the death and leave any blood stains on
	self:RemoveAllStatusEffects("death")
	if self.villain then
		local attackerMerc = attacker and IsMerc(attacker)
		
		if self.DefeatBehavior == "Defeated" then
			self:SetBehavior("VillainDefeat")
			self:SetCombatBehavior("VillainDefeat")
			self.villain_defeated = true
			self:SetCommand("VillainDefeat")
		elseif self.DefeatBehavior == "Dead" then
			if attackerMerc and SideIsEnemy(self.team.side, attacker.team.side) then
				PlayVoiceResponse(self, "DramaticDeath")
			end
			Msg("VillainDefeated", self, attacker)
			self.villain_defeated = true
		end
	end
	self.HitPoints = 0 -- in case statuses do some shenanigans I guess
	self.time_of_death = Game.CampaignTime
	self.pending_aware_state = nil
	self.killed_stance = self.stance

	Msg("UnitDieStart", self, attacker)
	Msg("UnitDiedOnSector", self, gv_CurrentSectorId)
	self.throw_died_message = "pre-sync"
	
	self:InterruptPreparedAttack()
	self:EndInterruptableMovement()
	CombatActionInterruped(self)
	for _, unit in ipairs(g_Units) do
		if unit:GetBandageTarget() == self then
			unit:SetCommand("EndCombatBandage")
		end
	end	
	local stealth_kill = hit_descr.stealth_kill
	if not attacker then
		CombatLog("debug", T{Untranslated("  <em><name></em> was <em>killed</em>"), name = self:GetLogName()})
	end

	results.glory_kill = not self.immortal and not hit_descr.grazing and self:Random(100) < const.Combat.GloryKillChance
	
	local death_explosion = hit_descr.death_explosion
	if self:GetItemInSlot("Inventory", "Valuables") or self:GetItemInSlot("Inventory", "QuestItem") then
		death_explosion = false
		hit_descr.death_explosion = false
	end

	if death_explosion then
		PlayFX("DeathExplosion", "start", self, target_spot_group)
	elseif results.glory_kill and IsKindOf(hit_descr.weapon, "Firearm") and not self.immortal and headshot and self.species == "Human" and self.parts.Head then
		self:SetHeadshot(true)
		PlayFX("Death", "start", self, "Headshot")
	else
		PlayFX("Death", "start", self, target_spot_group)
	end
	
	if IsMerc(self) then
		PlayFX("MercDeath", "start", self)
	end

	self:SetPos(self:GetVisualPos())
	self:SetHierarchyGameFlags(const.gofOnRoof) --hide with roofs and walls if too close to one
	self:ClearPath()
	self:ClearEnumFlags(const.efResting)
	self:SetTargetDummy(false)
	SetCombatActionState(self, nil)
	-- Remember the anim prefix when the unit died as it will drop its items
	self.die_anim_prefix = self:GetWeaponAnimPrefix()

	local container
	if not self.immortal then
		if death_explosion then
			container = GetDropContainer(self)
			container:SetVisible(false)
		end
		self:DropLoot(container)
		if container and not container:HasItem() then
			DoneObject(container)
			container = false
		end
	end
	self:SyncWithSession("map")
	self.throw_died_message = "after-start"

	if self.villain and self.DefeatBehavior == "Dead" then
		MoraleModifierEvent("LieutenantDefeated", self)
	else
		MoraleModifierEvent("UnitDied", self)
		if attacker and self.team.side ~= "neutral" and self.team.side ~= "player1" and self.team.side ~= "player2" and results.glory_kill then
			MoraleModifierEvent("SpectacularKill", attacker)
		end
	end

	-- alerts: noise (non-stealth only) and killed (always)
	local alerted, suspicious = PushUnitAlert("death", self)
	if not stealth_kill then
		local noise_alerted, noise_suspicious = PushUnitAlert("noise", self, const.Combat.DeathNoiseRange, Presets.NoiseTypes.Default.Pain.display_name)
		alerted, suspicious = alerted + noise_alerted, suspicious + noise_suspicious
	end
	if g_Combat and IsKindOf(attacker, "Unit") and not g_Combat:ShouldEndCombat() then
		if stealth_kill and alerted == 0 then
			PlayVoiceResponse(attacker, "OpponentKilledStealth")
		end
	end

	-- skip end combat check if the death made someone suspicious or alert
	-- note: a stealth kill attack wouldn't alert/raise suspicion in other units except through the "death" trigger
	local end_combat_check = g_Combat and suspicious + alerted == 0 and not g_AIExecutionController

	self:PushDestructor(function(self)
		self:RemovePreparedAttackVisuals()
		Msg("ActionCameraWaitSignalEnd")
		if container then
			container:SetVisible(true)
		end
	end)
	self:PushDestructor(function(self)
		assert(not self.command and not self:IsValid(), "Die command should not be interrupted (new command: " .. tostring(self.command) .. ").")
	end)
	-- wait a bit for possible destruction around or below the unit (bullets and explosions might destroy stuff after the unit)
	if not skip_anim then
		Sleep(100)
		self:StopPain()
	end
	self:PlayDying(skip_anim, end_combat_check)
	self:PopDestructor()
	self:PopAndCallDestructor()

	ObjModified(self)
	Msg("UnitDied", self, attacker, results)
	self.throw_died_message = false
	
	if IsValid(self) then
		self:BeginInterruptableMovement()
		self:SetCommand("Dead")
	end
end

local FX_Explosion_Variants = {
	"FX_Explosion_Human_01",
	"FX_Explosion_Human_02",
	"FX_Explosion_Human_03",
}

function Unit:PlaceDeathFXObject(quick_play, pos, angle)
	local x, y, z = FindFallDownPos(pos or self)
	if not x then
		if pos then
			x, y, z = pos:xyz()
		else
			x, y, z = self:GetPosXYZ()
		end
	end
	angle = angle or self:GetOrientationAngle()
	self:SetOpacity(0)
	local o = self.death_fx_object
	if not IsValid(o) then
		if not FX_Explosion_Variants[self.death_explosion_played] then
			self.death_explosion_played = 1 + self:Random(#FX_Explosion_Variants)
		end
		o = PlaceObject(FX_Explosion_Variants[self.death_explosion_played])
		o:SetStateText("idle")
		self.death_fx_object = o
	end
	if quick_play then
		o:SetAnimPhase(1, GetAnimDuration(o:GetEntity(), o:GetAnim(1)) - 1)
	end
	local orient_time = (quick_play or not o:IsValidPos()) and 0 or 500
	o:SetPos(x, y, z or const.InvalidZ, orient_time) -- fall down when destruction
	o:SetGroundOrientation(angle, orient_time, const.SlabSizeX * 40 / 100) -- one tile inclination
end

function Unit:PlayDying(quick_play, end_combat_check, anim, pos, angle, break_obj)
	local in_dead_anim
	local hit_descr = self.on_die_hit_descr
	local death_explosion = hit_descr and hit_descr.death_explosion or self.species == "Hen"
	local falldown_callback = hit_descr and hit_descr.falldown_callback and _G[hit_descr.falldown_callback]
	if death_explosion or string.match(self:GetStateText(), "Death") then
		in_dead_anim = true
		anim = self:GetStateText()
	end
	if not in_dead_anim and ShouldDoDestructionPass() then
		WaitMsg("DestructionPassDone", 1000)
	end
	if (not anim or not self:HasAnim(anim)) and not death_explosion then
		anim, pos, angle, break_obj = GetRandomDeathAnim(self, { attacker = self.on_die_attacker, hit_descr = hit_descr } )
	end
	local x, y, z = FindFallDownPos(pos or self)
	if not pos or x and not pos:Equal(x, y, z) then
		pos = x and point(x, y, z) or self:GetPos()
	end
	angle = angle or self:GetOrientationAngle()
	local orient_time = quick_play and 0 or 500
	self:DestroyAttaches("WeaponVisual")

	local behavior_params = { anim, angle }
	self:SetBehavior("Dead", behavior_params)
	self:SetCombatBehavior("Dead", behavior_params)

	if death_explosion then
		if self.death_explosion_played then
			quick_play = true
		end
		if not quick_play then
			Sleep(const.Combat.DeathExplosion_AnimationDelay)
		end
		self:SetBehavior("Despawn", behavior_params)
		self:SetCombatBehavior("Despawn", behavior_params)
		if self.species == "Hen" then
			local dlg = GetInGameInterfaceModeDlg()
			if IsKindOf(dlg, "IModeCombatAttackBase") and dlg:GetAttackTarget() == self then
				if g_Combat or g_StartingCombat then
					SetInGameInterfaceMode("IModeCombatMovement")
				else
					SetInGameInterfaceMode("IModeExploration")
				end
			end
			self:QueueCommand("Despawn")
			return
		end
		if IsValid(self.death_fx_object) then
			self:PlaceDeathFXObject(true, pos, angle)
			return
		end
		self:PlaceDeathFXObject(quick_play, pos, angle)
		if end_combat_check and g_Combat then
			g_Combat:EndCombatCheck()
		end
		if not quick_play and IsValid(self.death_fx_object) then
			Sleep(self.death_fx_object:TimeToAnimEnd())
		end
		return
	end

	if in_dead_anim then
		-- unconscious
		if end_combat_check and g_Combat then
			g_Combat:EndCombatCheck()
		end
		if quick_play then
			self:SetAnimPhase(1, GetAnimDuration(self:GetEntity(), anim) - 1)
		else
			Sleep(self:TimeToAnimEnd())
		end
		return
	end

	if quick_play then
		self:SetState(anim, 0, 0)
		local duration = GetAnimDuration(self:GetEntity(), anim)
		self:SetAnimPhase(1, duration - 1)
		self:SetPos(pos)
		self:SetFootPlant(true, 0)
		self:SetOrientationAngle(angle)
		if falldown_callback then
			falldown_callback(self.on_die_attacker, self, pos)
		end
		if IsValid(break_obj) and break_obj.pass_through_state == "intact" then
			break_obj:SetWindowState("broken")
		end
		if end_combat_check and g_Combat then
			g_Combat:EndCombatCheck()
		end
		return
	end
	local thread1, thread2
	self:PushDestructor(function(self)
		DeleteThread(thread1)
		DeleteThread(thread2)
		if IsValid(self) then
			self:PlayDying(true, false, anim, pos, angle, break_obj)
		end
	end)
	if falldown_callback then
		local delay = self:GetAnimMoment(anim, "hit") or self:GetAnimMoment(anim, "end") or self:GetAnimDuration(anim) - 1
		thread1 = CreateGameTimeThread(function(self, delay, pos, end_combat_check)
			Sleep(delay)
			local hit_descr = self.on_die_hit_descr
			local falldown_callback = hit_descr.falldown_callback and _G[hit_descr.falldown_callback]
			if falldown_callback then
				falldown_callback(self.on_die_attacker, self, pos)
			end
			if end_combat_check and g_Combat then
				g_Combat:EndCombatCheck()
			end
		end, self, delay, pos, end_combat_check)
	end
	if break_obj then
		local delay = self:GetAnimMoment(anim, "explosion") or 0
		thread2 = CreateGameTimeThread(function(delay, obj, end_combat_check)
			Sleep(delay)
			if IsValid(obj) and obj.pass_through_state == "intact" then
				obj:SetWindowState("broken")
			end
			if end_combat_check and g_Combat then
				g_Combat:EndCombatCheck()
			end
		end, delay, break_obj, end_combat_check)
	else
		if end_combat_check and g_Combat then
			g_Combat:EndCombatCheck()
		end
	end
	self:MovePlayAnim(anim, self:GetPos(), pos, 0, nil, true, angle)
	self:PopDestructor()
end

Unit.IsDead = UnitProperties.IsDead

function Unit:IsDefeatedVillain()
	return self.villain and self.villain_defeated
end

function Unit:RemoveEnemyPindown()
	if g_Combat then
		for attacker, descr in pairs(g_Pindown) do
			if descr.target == self then
				attacker:InterruptPreparedAttack()
			end
		end
	end
end

DefineClass.DecFXBlood_01 = {__parents = {"Object"}}

function Unit:PlaceBlood()
	if self:HasPassedTimeAfterDeath(const.Satellite.RemoveBloodAfter) then
		--do not place blood if const.Satellite.RemoveBloodAfter has passed
		return
	end
	local blood_pos = self:GetSpotVisualPos(self:GetSpotBeginIndex("Blood"))
	blood_pos = blood_pos:SetZ(self:GetVisualPos():z())
	local blood = PlaceObject("DecFXBlood_01")
	blood:SetGameFlags(const.gofDecalOpacityAlphaTest)
	blood:SetPos(blood_pos)
	blood:SetAngle(self:Random(360 * 60))
	blood:SetOpacity(0)
	blood:SetOpacity(95, 4000 + self:Random(2000))
end

function Unit:Dead(anim, angle)
	local behavior = g_Combat and self.combat_behavior or self.behavior
	if behavior == "Despawn" then
		return
	end
	
	-- Savegame fixup for 241898
	-- Errored/save-load during death before loot is dropped
	if self:CountItemsInSlot("Inventory") ~= 0 and self:CountItemsInSlot("InventoryDead") == 0 then
		self.throw_died_message = "pre-sync"
	end
	
	-- Savegame fixup for 238866
	-- Errored in RemoveStatusEffect BandageInCombat prior to moving throw_died_message above that call.
	if not self.time_of_death then
		self.throw_died_message = "all"
	end
	
	-- This can happen when a save is made while the unit was running the "Die" command.
	-- Upon load the unit will be dead (go straight here) without having thrown the message,
	-- which could mean that the conflict isn't resolved.
	if self.throw_died_message then
		if self.throw_died_message == true then -- legacy
			self.throw_died_message = "all"
		end
	
		local killer = self.on_die_attacker
		if self.throw_died_message == "all" then
			if self.villain then
				Msg("VillainDefeated", self, killer)
			end
			
			self.time_of_death = Game.CampaignTime
			Msg("UnitDieStart", self, killer)
			Msg("UnitDiedOnSector", self, gv_CurrentSectorId)
			self.throw_died_message = "pre-sync"
		end
		
		if self.throw_died_message == "pre-sync" then
			local container = GetDropContainer(self)
			if not self.immortal then
				self:DropLoot(container)
			end
			if container and not container:HasItem() then
				DoneObject(container)
				container = false
			end
			self:SyncWithSession("map")
			self.throw_died_message = "after-start"
		end

		Msg("UnitDied", self, killer, empty_table)
		self.throw_died_message = false
	end
	
	-- some Die command code is repeated here for the cases when the Die command was skipped (load a game)
	self:SetHierarchyGameFlags(const.gofOnRoof) --hide with roofs and walls if too close to one
	self:ClearPath()
	self:ClearEnumFlags(const.efResting)
	self:SetTargetDummy(false)
	SetCombatActionState(self, nil)
	self:RemoveEnemyPindown()
	if self.species == "Human" then
		self.stance = "Prone"
	end

	if not anim and self.behavior == "Dead" then
		anim, angle = table.unpack(self.behavior_params or empty_table)
	end
	self:PlayDying(true, false, anim, nil, angle)
	self:PlaceALDeadMarkers()

	Halt()
end

function Unit:Hang()
	SetCombatActionState(self, nil)
	self:SetBehavior("Hang")
	self:SetCombatBehavior("Hang")
	
	local ropes = MapGet("map", "World_HangingRope") or empty_table
	if #ropes ~= 1 then
		StoreErrorSource(point30, "There should be one rope on the map.")
		return
	end
	local rope = ropes[1]
	local hanging_spot_idx = rope:GetSpotBeginIndex("Hanging")
	if hanging_spot_idx == -1 then
		StoreErrorSource(rope, "Rope missing Hanging spot")
		return
	end
	rope.SetAutoAttachMode = empty_func
	self:ClearEnumFlags(const.efApplyToGrids)
	self:ClearEnumFlags(const.efCollision)
	--this unit is goind to be attached to a bone anim;
	--in order to not net check its saved position/axis/angle on enter sector which could be a little different per client
	--we clear the sync flag and switch its class to a class with gofSyncObject = false
	self:MakeNotSync()
	rope:Attach(self, hanging_spot_idx)
	self:SetState("nw_Hanging", 0, 0)
	self.HitPoints = 0
	self.immortal = false
	InvalidateDiplomacy()
	Msg("UnitDieStart", self)
	Halt()
end

DefineClass.NonSyncUnit = {
	__parents = { "Unit" },
	flags = { gofSyncObject = false },
}

function Unit:MakeNotSync()
	if not self:IsSyncObject() then return end
	self:ClearGameFlags(const.gofSyncObject)
	--self:SetHandle(self:GenerateHandle()) --its probably fine to leave the old handle in case someone is refering to this
	setmetatable(self, g_Classes.NonSyncUnit)
end

function Unit:IsPersistentDead()
	return self.command == "Hang"
end

function Unit:VillainDefeat()
	if not self.villain or not self.villain_defeated then
		if self.behavior == "VillainDefeat" then
			self:SetBehavior()
		end
		if self.combat_behavior == "VillainDefeat" then
			self:SetCombatBehavior()
		end
		return
	end
	
	SetCombatActionState(self, nil)
	if SideIsEnemy(self.team.side, "player1") then
		PlayVoiceResponse(self, "VillainDefeated")
	end
	
	self:SetBehavior("VillainDefeat")
	self:SetCombatBehavior("VillainDefeat")
	
	self.invulnerable = true
	self.conflict_ignore = true -- prevent ambient life from messing around with this unit
	self.neutral_retaliate = false
	self.HitPoints = 1
	self:DoChangeStance("Crouch")
	self.ActionPoints = 0
	self.villain_defeated = true
	self:ClearPath()

	self:InterruptPreparedAttack()
	self:RemoveAllStatusEffects()
	
	local squad = gv_Squads[self.Squad]
	if squad then
		local newSquadId = SplitSquad(squad, {self.session_id})
		assert(self.Squad == newSquadId)
		SetSatelliteSquadSide(self.Squad, "neutral")
	end
	self:SetSide("neutral")
	
	MoraleModifierEvent("LieutenantDefeated", self)

	if g_Combat and not g_AIExecutionController then
		g_Combat:EndCombatCheck()
	end

	self:RemoveEnemyPindown()

	-- temporary anim
	self.command_specific_params = self.command_specific_params or {}
	self.command_specific_params.VillainDefeat = { weapon_anim_prefix = "civ_" }
	self:SetRandomAnim(self:GetIdleBaseAnim("Crouch"), const.eKeepComponentTargets, 0)
	self:SyncWithSession("map")
	Msg("VillainDefeated", self, self.on_die_attacker)
	Halt()
end

function Unit:Despawn()
	self:AutoRemoveCombatEffects()
	self:InterruptPreparedAttack()
	self:RemoveEnemyPindown()
	
	--remove crosshair on despawned unit
	local dlg = GetInGameInterfaceModeDlg()
	local crosshair = dlg and dlg.crosshair
	if crosshair and crosshair.context.target == self then
		dlg:RemoveCrosshair("Despawn")
		if g_Combat then
			if g_Combat:ShouldEndCombat() then
				g_Combat:EndCombatCheck(true)
			else
				SetInGameInterfaceMode("IModeCombatMovement")
			end
		else
			SetInGameInterfaceMode("IModeExploration", {suppress_camera_init = true})
		end
	end
	
	if not self:IsAmbientUnit() then self:SyncWithSession("map") end
	self.is_despawned = true
	--self:RemoveAllStatusEffects()
	if SelectedObj == self then
		SelectObj()
	end
	local cameraFollowTarget = cameraTac.GetFollowTarget()
	if cameraFollowTarget == self then
		cameraTac.SetFollowTarget(false)
	end
	if self.Squad then
		local squad = gv_Squads[self.Squad]
		if squad and (squad.Side == "enemy1" or squad.Side == "enemy2") then
			RemoveUnitFromSquad(gv_UnitData[self.session_id])
		end
	elseif not IsMerc(self) and not self.PersistentSessionId then
		gv_UnitData[self.session_id] = nil
	end
	
	if g_Combat and  not self:IsLocalPlayerControlled() and CountAnyEnemies()==1 then
		g_Combat.retreat_enemies = true
	end
	DoneObject(self)
	
	if g_Combat and not g_AIExecutionController then
		g_Combat:EndCombatCheck("force")
	end
end

function Unit:CanActivatePerk(id)
	return HasPerk(self, id) and not self.perks_activated[id] and not self:IsDead()
end

function Unit:ActivatePerk(id)
	if self.perks_activated then
		self.perks_activated[id] = true
	end
end

function Unit:GetUIActionPoints()
	return self.ui_override_ap or Max(0, (self.ActionPoints or 0) - self.ui_reserved_ap - self.free_move_ap)
end

function Unit:GetUIAdjustedActionCost(ap, movement, use_free_move)
	local ap_scale = const.Scale.AP
	local ap_now = self:GetUIActionPoints() / ap_scale
	local free
	if movement then
		local unit_ap = self.ActionPoints
		if not use_free_move then
			unit_ap = Max(0, unit_ap - SelectedObj.free_move_ap)
		end
		local ap_after = Max(0, unit_ap - ap) / ap_scale
		if ap_after >= ap_now then
			ap = 0
			if use_free_move and ap <= self.free_move_ap then
				free = true
			end
		else
			ap = ap_now - ap_after
		end
	else
		ap = ap / const.Scale.AP
	end
	
	return ap, ap_now, free
end

function Unit:UIHasAP(ap, action_id, args)
	return self:HasAP((ap or 0) + self.ui_reserved_ap, action_id, args)
end

function Unit:HasAP(ap, action_id, args)
	if not g_Combat and not g_StartingCombat and not g_TestingSaveLoadSystem then
		return true
		--self.ActionPoints = self:GetMaxActionPoints()
	end
	local move_ap = 0
	local action = CombatActions[action_id]
	if action and action.UseFreeMove then
		if args and args.ap_cost_breakdown then
			move_ap = args.ap_cost_breakdown.move_cost or ap
		else
			move_ap = ap
		end
	else
		move_ap = args and args.goto_ap or 0
	end
	-- available ap for the action are the base AP + free move ap up to move_ap (when 0, that's the base AP only)
	local available = Max(0, (self.ActionPoints or 0) - self.free_move_ap) + Min(move_ap, self.free_move_ap)	
	return (available or 0) >= (ap or 0), (ap or 0) - (available or 0)
end

function Unit:GainAP(ap)
	if not g_Combat or (ap or 0) <= 0 then
		return
	end
	if g_Pindown[self] or (g_Overwatch[self] and not g_Overwatch[self].permanent) or self:IsDowned() then
		return
	end
	if self:HasStatusEffect("Panicked") or self:HasStatusEffect("Berserk") or self:HasStatusEffect("Protected") then
		return
	end
	local spentAp = self:GetStatusEffect("SpentAP")
	if spentAp and spentAp.stacks >= self:GetMaxActionPoints() then
		return
	end

	self.ActionPoints = self.ActionPoints + ap
	CombatPathReset(self)
	Msg("UnitAPChanged", self)
	ObjModified(self)
end

function Unit:ConsumeAP(ap, action_id, args)
	ap = ap or 0
	
	local action = action_id and CombatActions[action_id]
	if action and ap > 0 then
		if action.ActionType ~= "Ranged Attack" and action.ActionType ~= "Melee Attack" then
			self:RemoveStatusEffect("Focused")
		end
		if action.ActionType == "Ranged Attack" or action.ActionType ==  "Melee Attack" then
			self:RemoveStatusEffect("Mobile")
			self:RemoveStatusEffect("FreeMove")
		end
	end
	
	if action then
		if action_id ~= "ChangeWeapon" then
			self.performed_action_this_turn = action_id
		end
	end
	
	local move_ap = 0
	if action and action.UseFreeMove then
		move_ap = ap
	else
		move_ap = args and args.goto_ap or 0
	end
	if move_ap > 0 then
		self.start_move_total_ap = self.ActionPoints
		self.start_move_cost_ap = move_ap
		self.start_move_free_ap = self.free_move_ap
	
		local reduce = Min(move_ap, self.free_move_ap)
		self.free_move_ap = self.free_move_ap - reduce
	end
	
	if not g_Combat or ap <= 0 or self.infinite_ap then
		return
	end
	self.ActionPoints = Max(0, self.ActionPoints - ap)
	Msg("UnitAPChanged", self, action_id, -ap)
	ObjModified(self)
end

function OnMsg.UnitAPChanged()
	if not GetDialog("PDADialogSatellite") then
		ObjModified("combat_bar")
	end
end

function OnMsg.CombatActionEnd(unit)
	unit.start_move_total_ap = nil
	unit.start_move_cost_ap = nil
	unit.start_move_free_ap = nil
end

function Unit:AddStatusEffect(effect, ...)
	NetUpdateHash("AddStatusEffect", self, effect)
	if self:IsDead() then return end
	if effect == "Bleeding" and self:IsDead() then
		return
	end
	if (effect == "Tired" or effect == "Exhausted") and not g_Combat then
		PlayVoiceResponse(self, effect)
	end
	return StatusEffectObject.AddStatusEffect(self, effect, ...)
end

function Unit:RemoveStatusEffect(effect, ...)
	if self.StatusEffects[effect] then
		NetUpdateHash("RemoveStatusEffect", self, effect)
	end
	return StatusEffectObject.RemoveStatusEffect(self, effect, ...)
end

function NetEvents.UnitAddPerk(session_id, perk_id)
	local unit = g_Units[session_id]
	if unit then
		unit:AddStatusEffect(perk_id)
	end
	local unit = gv_UnitData[session_id]
	if unit then
		unit:AddStatusEffect(perk_id)
	end
end

function Unit:TakeDamage(dmg, attacker, hit_descr, ...)
	if g_Combat then
		g_Combat:OnUnitDamaged(self, attacker)
	end

	-- lose Hidden and alert units around visually and vocally (unless killed from stealth)
	self:RemoveStatusEffect("Hidden")
	if not hit_descr.stealth_kill and not hit_descr.melee_attack and not hit_descr.setpiece then
		TriggerUnitAlert("noise", self, const.Combat.PainNoiseRangeStealthKill, Presets.NoiseTypes.Default.Gunshot.display_name, attacker)
	end
	
	if IsKindOf(attacker, "Unit") then
		self.hit_this_turn = self.hit_this_turn or {}
		table.insert(self.hit_this_turn, attacker)
	end

	if self:IsInvulnerable() and not hit_descr.setpiece then
		CreateFloatingText(self:GetVisualPos(), T(759740141426, "Invulnerable"))
		CombatLog("debug", T{Untranslated("<name> has ignored <num> damage (invulnerable)"), name = self:GetLogName(), num = dmg})
		return
	end

	return CombatObject.TakeDamage(self, dmg, attacker, hit_descr, ...)
end

function Unit:TakeDirectDamage(dmg, floating, log_type, log_msg, attacker, hit_descr)
	hit_descr = hit_descr or {}
	-- ignore damage from the same action that downed us
	if self:IsDowned() and self.downing_action_start_time == CombatActions_LastStartedAction.start_time then
		return
	end

	local data = { dmg = dmg, hit_descr = hit_descr }
	Msg("PreUnitDamaged", attacker, self, data)
	dmg = data.dmg
	dmg = self:CallReactions_Modify("PreUnitTakeDamage", dmg, attacker, self, hit_descr)
	if IsKindOf(attacker, "Unit") then
		dmg = attacker:CallReactions_Modify("PreUnitTakeDamage", dmg, attacker, self, hit_descr)
	end
	if dmg <= 0 then return end
	
	local hp = self.HitPoints
	local tempHp = self.TempHitPoints
	hit_descr.was_downed = self:IsDowned()
	CombatObject.TakeDirectDamage(self, dmg, floating, log_type, log_msg, attacker, hit_descr)
	self.last_turn_damaged = true

	if not self:IsDead() then
		local healthDamageTaken = self.HitPoints < hp or (dmg > 0 and (self.invulnerable or CheatEnabled("WeakDamage")))
		local gritDamageTaken = self.TempHitPoints < tempHp or (dmg > 0 and (self.invulnerable or CheatEnabled("WeakDamage")))
		if healthDamageTaken then
			MoraleModifierEvent("UnitDamaged", self, hp - self.HitPoints)
			if not (hit_descr and hit_descr.grazing) then
				self:AccumulateDamageTaken(hp - self.HitPoints)
			end
		end
		if healthDamageTaken or gritDamageTaken or hit_descr.setpiece then
			if not hit_descr.grazing then
				self:Pain(hit_descr, attacker)
			end
			self:RemoveStatusEffect("Hidden")
		end
	end

	if hit_descr and hit_descr.explosion_fly and not self:IsMerc() then
		if not self:IsDead() then
			self:Interrupt()
		end
		self:InterruptCommand("ExplosionFly", hp)
	end

	ObjModified(self)
end

function Unit:OnHPLoss(hp, attacker)
	if g_Combat and g_Combat.hp_loss then
		g_Combat.hp_loss[self.session_id] = (g_Combat.hp_loss[self.session_id] or 0) + hp
	end
end

function Unit:StopPain()
	if self.pain_thread then
		self:ClearAnim(const.AnimChannel_Pain)
		DeleteThread(self.pain_thread)
		self.pain_thread = false
	end
end

function Unit:WaitPain()
	while IsValidThread(self.pain_thread) do
		WaitMsg(self.pain_thread, 1000)
	end
end

function Unit:PlayPainAnim(alert_units)
	self:SetPos(self:GetVisualPos())
	self:SetAngle(self:GetVisualAngle())
	local anim = self:GetRandomAnim("pain")
	self:SetState(anim)
	repeat until not WaitWakeup(self:TimeToAnimEnd())
	self:SetState(self:GetIdleBaseAnim())
	if alert_units then
		AlertPendingUnits()
	end
end

local function GetPainAnim(unit, prefix, stance, variant)
	local anim = string.format("%s_%s_Pain%s", prefix, stance, variant == 1 and "" or variant)
	if IsValidAnim(unit, anim) then
		return anim
	end
	if variant > 1 then
		anim = string.format("%s_%s_Pain", prefix, stance)
		if IsValidAnim(unit, anim) then
			return anim
		end
	end
end

function Unit:Pain(hit_descr, attacker)
	local setpiece = hit_descr and hit_descr.setpiece
	local alert_units = not setpiece
	if alert_units then
		TriggerUnitAlert("noise", self, const.Combat.PainNoiseRange, Presets.NoiseTypes.Default.Pain.display_name, attacker) -- dead units do not play pain
	end

	if self.species ~= "Human" then
		DeleteThread(self.pain_thread)
		self.pain_thread = nil
		if self:HasStatusEffect("Unconscious") then
			return
		end
		if self.interrupted then
			self.pain_thread = CreateGameTimeThread(function(self, alert_units)
				self:PlayPainAnim(alert_units)
				self.pain_thread = false
				Msg(CurrentThread())
			end, self, alert_units)
		elseif self:IsInterruptable() and CurrentThread() ~= self.command_thread then
			self:SetCommand("PlayPainAnim", alert_units)
		elseif alert_units then
			AlertPendingUnits()
		end
		return
	end

	local anim
	if self:HasAnimMask("PainMask") then   --"UpperBodyMask"
		local prefix = string.match(self:GetStateText(), "^(%a+)_%a+_.*") 
		if not prefix and setpiece then
			prefix = string.match(self:GetWeaponAnimPrefix(), "^(%a+)_")
		end
		local target_spot_group = hit_descr and hit_descr.spot_group
		local variant = target_spot_group == "Head" and 3 or 1 + self:Random(2)
		local stance = self.infected and "Standing" or self.stance
		anim = GetPainAnim(self, prefix, stance, variant)
		if not anim and prefix == "arg" then
			anim = GetPainAnim(self, "ar", stance, variant)
		end
		if not anim and prefix == "inf" then
			anim = GetPainAnim(self, "nw", stance, variant)
		end
	end
	if not (anim and IsValidAnim(self, anim)) then
		if alert_units then
			AlertPendingUnits()
		end
		return
	end

	local channel = const.AnimChannel_Pain
	local pain_anim_weight = hit_descr and hit_descr.grazing and const.PainAnimGrazingWeight or const.PainAnimWeight
	self:SetAnimMask(channel, "PainMask") --"UpperBodyMask"
	self:SetAnim(channel, anim, 0, -1, 1000, 0)
	self:SetAnimWeight(channel, pain_anim_weight, const.PainAnimWeightMoment, PainEasing)
	self:SetAnimBlendComponents(channel, false, true, false)
	DeleteThread(self.pain_thread)
	self.pain_thread = CreateGameTimeThread(function(self, anim, alert_units)
		Sleep(const.PainAnimWeightMoment)
		local channel = const.AnimChannel_Pain
		repeat
			local t = self:TimeToAnimEnd(channel)
			self:SetAnimWeight(channel, 0, t, 1, PainEasing)
		until not WaitWakeup(t)
		self:ClearAnim(channel)
		self.pain_thread = false
		if alert_units then
			AlertPendingUnits()
		end
		Msg(CurrentThread())
	end, self, anim, alert_units)
end

function Unit:KnockDown()
	if self.species ~= "Human" or self:IsDead() then
		return
	end
	local base_anim = self:GetActionBaseAnim("Downed", self.stance)
	local anim = self:GetStateText()
	if not IsAnimVariant(anim, base_anim) then
		anim = self:GetNearbyUniqueRandomAnim(base_anim)
	end
	--self:PushDestructor(function(self)
		self.return_pos = nil
		self:InterruptPreparedAttack() -- force interrupt when the unit gets knocked down
		if self:GetStateText() ~= anim then
			local x, y, z = FindFallDownPos(self)
			local pos = x and point(x, y, z) or self:GetPos()
			local angle = self:GetOrientationAngle()
			self:SetOrientationAngle(angle, 300)
			self:MovePlayAnim(anim, pos, pos, 0, nil, true, angle)
		end
		local variation_suffix = string.match(anim, "(%d+)$") -- there are no variations for now
		local idle_anim = self:TryGetActionAnim("Idle", "Downed", variation_suffix)
		if idle_anim then
			self:SetState(idle_anim, 0, 0)
		end
		self.stance = self:GetValidStance("Prone")
		self:SetFootPlant(true)
		self:SetTargetDummy(nil, nil, nil, 0) -- current position, animation phase 0
		--self:DoChangeStance("Prone")
		self:RemoveStatusEffect("KnockDown")
		self:RemoveStatusEffect("Protected") -- lose cover
	--end)
	--self:PopAndCallDestructor()
	if self:HasStatusEffect("Unconscious") then
		self:SetCommand("Downed")
	end
end

function Unit:Dodge()
	self:SetFootPlant(true)
	local anim = self:GetActionRandomAnim("Dodge", self.stance)
	self:SetState(anim, const.eKeepComponentTargets)
	Sleep(self:TimeToAnimEnd())
end

function Unit:BeginTurn(new_turn)
	NetUpdateHash("BeginTurn_Start")
	self:SetAttackReason()
	local should_interrupt = true
	local pindown = g_Pindown[self]
	local overwatch = g_Overwatch[self]
	if pindown and IsValidTarget(pindown.target) and self:HasPindownLine(pindown.target, pindown.target_spot_group) then
		-- pindown will be handled differently when the attack is executed
		should_interrupt = false
	elseif overwatch and (overwatch.permanent or not g_Combat or overwatch.expiration_turn > g_Combat.current_turn) then
		should_interrupt = false
	elseif self.prepared_bombard_zone then
		should_interrupt = false
	end	
	if new_turn and should_interrupt then 
		self:InterruptPreparedAttack("begin turn")
		pindown = false
	end
	self:UpdateMeleeTrainingVisual()
	self:IsThreatened() -- update the is_melee_aim_last_turn flag for the vr
	
	if self.is_melee_aim_last_turn and IsMerc(self) then		
		PlayVoiceResponse(self, "MeleeEnemiesClosing")
		self.is_melee_aim_last_turn = false
	end

	self.perks_activated = {}
	NetUpdateHash("BeginTurn_Progress")
	if new_turn then
		self:RemoveStatusEffect("FreeMove")
		if g_Overwatch[self] and not g_Overwatch[self].permanent then
			self.ActionPoints = 0 -- special-case for carrying an overwatch from exploration mode
		else
			local ap = self:GetMaxActionPoints()
			ap = self:CallReactions_Modify("OnCalcStartTurnAP", ap)
			self.ActionPoints = Max(0, ap)
			
--			if g_Combat.current_turn == 1 and self:IsMerc() then --use this to test lower AP during the first turn
--				self.ActionPoints = MulDivRound(self.ActionPoints, 75, 100)
--			end
		end
		if g_Overwatch[self] then
			table.clear(g_Overwatch[self].triggered_by) -- reset triggers in case somebody already triggered in our turn
			if self:HasStatusEffect("ManningEmplacement") or self:HasStatusEffect("StationedMachineGun") then
				g_Overwatch[self].num_attacks = self:GetNumMGInterruptAttacks()
				self:UpdateOverwatchVisual()
			end
		end
		g_Pindown[self] = nil -- clear from the global table to stop the prepared attack blocking any AP gains
		self.ui_reserved_ap = 0
		
		if self:GetEffectValue("missed_by_kill_shot") and not self:IsDead() and not self:IsDowned() then
			PlayVoiceResponse(self, "MissedByKillShot")
			self:SetEffectValue("missed_by_kill_shot", nil)
		end
		
		self:UpdateHidden()
		
		local voxels = self:GetVisualVoxels()
		local fire, dist = AreVoxelsInFireRange(voxels)
		if fire then
			local min, max = const.BurnDamageMin, const.BurnDamageMax
			local damage = self:RandRange(min, max)
			self:TakeDirectDamage(damage)
			if not self:IsIncapacitated() and not self:HasStatusEffect("Unconscious") and not RollSkillCheck(self, "Health") then
				self:ChangeTired(1)
			end
			if dist < const.SlabSizeX then
				self:AddStatusEffect("Burning")
			end
		end
		
		self.attacked_this_turn = false
		self.hit_this_turn = false
		self.wounded_this_turn = false
		NetUpdateHash("BeginTurn", self, self.using_cumbersome, HasPerk(self, "KillingWind"),
								HasPerk(self, "Ironclad"))
		if not self.using_cumbersome or HasPerk(self, "KillingWind") then
			self:AddStatusEffect("FreeMove")
		elseif self:CanUseIroncladPerk() then
			self:AddStatusEffect("FreeMove")
			self:ConsumeAP(DivRound(self.free_move_ap, 2), "Move")
		end
		
		-- ConsumeAP will flag this only when an action is given, so it is safe to mark this a bit earlier to allow OnBeginTurn effects to alter it
		self.performed_action_this_turn = false
		
		Msg("UnitBeginTurn", self)
		self:CallReactions("OnBeginTurn")
		
		local morale = self:GetPersonalMorale()
		if morale > 0 then
			self:GainAP(morale * const.Scale.AP)
		elseif morale < 0 then
			self:ConsumeAP(Min(self.ActionPoints, -morale * const.Scale.AP))
		end
		
		if self:GetItemInSlot("Head", "GasMaskBase") then
			self:ConsumeAP(const.Scale.AP)
		end

		-- special-case: if the unit dies as a result of a status effect, show them and wait the command to end
		-- doing this here makes sure the camera will not immediately jump to another unit (dying or selected)
		-- similarly, executing the pindown attack has to be waited until it finishes
		if self.command == "Die" then
			SnapCameraToObj(self)
			while self.command == "Die" do
				WaitMsg("UnitDied", 20) -- can also go in VillainDefeat instead, so wait with timeout
			end
		elseif pindown then
			pindown.target:ProvokeOpportunityAttack_Pindown(self, pindown)
		elseif self.prepared_bombard_zone then
			self:StartBombard()
		end
	end
	
	if self.dummy or self:IsDowned() then
		self.ActionPoints = 0
	end

	self.start_turn_pos = self:GetVisualPos()
		
	NetUpdateHash("BeginTurn", self, self:GetPos())
	
	Msg("UnitAPChanged", self)
end

function AdjustWoundsToHP(obj,stacks)
	local effect = obj:GetStatusEffect("Wounded")
	local maxhp = obj:GetInitialMaxHitPoints()
	local value = Wounded:ResolveValue("MaxHpReductionPerStack")
	local maxreduce = Wounded:ResolveValue("MinMaxHp")
	local min = MulDivRound(maxhp, maxreduce, 100)
	local cur_stacks = effect and effect.stacks or 0
	local count = stacks and (cur_stacks + stacks) or cur_stacks
	while count>=0 do
		if maxhp - count * value >= min then
			if stacks then
				return count - cur_stacks
			end
			return count
		end
		count = count - 1
	end
	if stacks then
		return count - cur_stacks
	end
	return count
end

function RecalcMaxHitPoints(unit) -- unit can be Unit or UnitData
	local count = AdjustWoundsToHP(unit)
	if count and count>0 then
		local effect = unit:GetStatusEffect("Wounded")
		local to_remove = effect.stacks - count
		if to_remove>0 then
			unit:RemoveStatusEffect("Wounded", to_remove)
		end
	end
	local maxhp = unit:GetModifiedMaxHitPoints()
	local prev_maxhp = unit.MaxHitPoints
	unit.MaxHitPoints = maxhp
	if maxhp > prev_maxhp then
		unit.HitPoints = unit.HitPoints + maxhp - prev_maxhp
	end
	unit.HitPoints = Min(unit.HitPoints, unit.MaxHitPoints)
	ObjModified(unit)
end

function GetMedsAndOwners(units, healer, healed)
	local total_amount = 0
	local list, meds_list = {}, {}

	local function add_meds(unit, list)
		local meds = unit:GetItem("Meds")
		if meds then
			total_amount = total_amount + meds.Amount
			list[#list + 1] = meds
			list[#list + 1] = unit
			meds_list[unit.session_id] = (meds_list[unit.session_id] or 0) + meds.Amount
		end
	end

	if healer then
		add_meds(healer, list)
	end
	if healed and healed ~= healer then
		add_meds(healed, list)
	end

	for _, unit in ipairs(units) do
		if unit ~= healer and unit ~= healed then
			add_meds(unit, list)
		end
	end
	local squad_id = units and units[1] and units[1].Squad
	if squad_id then
		for _, meds in ipairs(GetSquadBag(squad_id)) do
			if meds.class == "Meds" then
				total_amount = total_amount + meds.Amount
				list[#list + 1] = meds
				list[#list + 1] = squad_id
				meds_list[squad_id] = (meds_list[squad_id] or 0) + meds.Amount
			end
		end
	end
	
	return total_amount, list, meds_list
end

function Unit:CalcHealAmount(medkit, target)
	if not medkit then return 0 end
	local base_heal = CombatActions.Bandage:ResolveValue("base_heal")
	local medical_heal = CombatActions.Bandage:ResolveValue("medical_max_heal")
	local selfheal = CombatActions.Bandage:ResolveValue("selfheal")

	local heal_percent = base_heal + MulDivRound(self.Medical, medical_heal, 100)
	local data = {
		heal_amount = 0,
		heal_percent = heal_percent,
		self_heal_percent = 50,
		heal_modifier = 100,
	}
	self:CallReactions("OnCalcHealAmount", target, self, medkit, data)
	if target ~= self and IsKindOf(target, "UnitBase") then
		target:CallReactions("OnCalcHealAmount", target, self, medkit, data)
	end
	
	local heal_percent = data.heal_percent
	if target == self then
		heal_percent = MulDivRound(heal_percent, data.self_heal_percent, 100)
	end
	local heal_mod = MulDivRound(heal_percent, data.heal_modifier, 100)
		
	-- convert to raw hp
	local max = IsValid(target) and target.MaxHitPoints or self.MaxHitPoints
	return data.heal_amount + MulDivRound(max, heal_mod, 100), MulDivRound(heal_percent, 100, heal_mod)
end

function Unit:OnEndTurn()
	self:RemoveStatusEffect("FreeMove") -- cleanup unused free move ap
	if self.start_turn_pos then -- Units hired during this turn don't have start_turn_pos
		self.last_turn_movement = self:GetVisualPos() - self.start_turn_pos
	else
		self.last_turn_movement = nil
	end
	self.last_turn_damaged = nil -- reset here, we're tracking damage done between the end of our turn and the start of our next one
	SetCombatActionState(self, false)
	
	-- add attacks from remaining AP to permanent overwatch
	self:UpdateNumOverwatchAttacks()
	
	Msg("UnitEndTurn", self)
	self:CallReactions("OnEndTurn")
	for i = #self.StatusEffects, 1, -1 do
		local effect = self.StatusEffects[i]
		if effect.lifetime ~= "Indefinite" then
			local expiration = self:GetEffectExpirationTurn(effect.class, "expiration")
			if g_Combat and g_Combat.current_turn >= expiration then
				self:RemoveStatusEffect(effect.class, "all")
			end
		end
	end
		
	-- special-case: if the unit dies as a result of a status effect, show them and wait the command to end
	-- doing this here makes sure the camera will not immediately jump to another unit (dying or selected)
	if self.command == "Die" then
		SnapCameraToObj(self)
		while self.command == "Die" do
			WaitMsg("UnitDied", 20) -- can also go in VillainDefeat instead, so wait with timeout
		end
	end
end

function Unit:OnCommandStart()
	if self.interrupted then
		self:InterruptEnd()
	end
	self.cur_idle_style = false
	self.cur_move_style = false
	self.goto_target = false
	self.goto_stance = false
	self.goto_hide = false
	self.visibility_override = false
	self.passed_interrupts = nil
	self:TunnelsUnblock()
	self.action_visual_weapon = false
	if IsValid(self) then
		self:SetGravity(0)
		self:StopMoving()
		self.interrupted = false
		if not self:IsDead() and not IsActivePaused() and not IsSetpieceActor(self) then
			self:ClearPath()
			if self.traverse_tunnel then
				local tpos = self.traverse_tunnel:GetExit()
				if tpos then
					local pos = GetPassSlab(tpos) or FindPassable(tpos, 0, -1, -1, const.pfmVoxelAligned) or tpos
					self:SetPos(pos)
				end
			end
		end
		if not KeepAimIKCommands[self.command] then
			self:SetWeaponLightFx(false)
			self:SetIK("AimIK", false)
		end
		self:SetIK("LookAtIK", false)
		if not self.interruptable and self.command then
			self:BeginInterruptableMovement()
		end
		self:SetFootPlant(true)
	end
	self.traverse_tunnel = false
	self:SetAimFX(false, self.command and "delayed")
	if self.action_command then
		SetCombatActionState(self, self.command == self.action_command and "start" or nil)
	end
end

function Unit:SetActionCommand(command, combatActionId, ...)
	-- the interface should clear the visualisations
	DbgClearVectors()
	DbgClearTexts()

	if IsActivePaused() then
		if CombatActions_RunningState[self] then
			SetCombatActionState(self)
		else
			self:SetQueuedAction()
		end
	end

	self.action_command = command
	SetCombatActionState(self, "wait")

	self:InterruptCommand(command, combatActionId, ...)
end

function Unit:IsLocalPlayerControlled(player_control_mask)
	return IsControlledByLocalPlayer(self.team and self.team.side, player_control_mask or self.ControlledBy)
end

function Unit:IsLocalPlayerTeam()
	if not netInGame then
		return self:IsLocalPlayerControlled()
	else
		local squad = self.team
		if not squad then return true end
		return squad.side == NetPlayerSide(netUniqueId)
	end
end

function Unit:IsControlledBy(mask)
	return self.ControlledBy & mask ~= 0
end

function Unit:IsDisabled()
	--the unit is in an uncontrollable state
	return self:IsIncapacitated() or self:HasStatusEffect("Panicked") or self:HasStatusEffect("Berserk")
end

--CanBeControlled() without args returns whether unit can be controlled by local player
--CanBeControlled("sync_code") returns whether unit can be controlled by any player in general omiting async reasons for control loss
function Unit:CanBeControlled(sync_code)
	if not IsValid(self) then return false end
	if GetDialog("ConversationDialog") then return false end

	--disabled units cannot be controlled
	if self:IsIncapacitated() then return false end
	--is it an AI team?
	if not self.team or self.team.control ~= "UI" then return false end
	
	--can it be controlled by the local player network wise?
	if not self:IsLocalPlayerControlled(sync_code and -1 or nil) then -- -1 is any net player
		return false 
	end
	
	-- Don't do further checks in deployment mode.
	if gv_DeploymentStarted then return true end
	
	if g_AIExecutionController or g_UnitAwarenessPending == "alert" then -- AI units taking actions
		return false
	end

	if g_Combat then
		if not g_Combat.combat_started then
			return false
		end
		-- Not current team in combat
		if not g_Combat:HasTeamTurnStarted(self.team) then
			return false
		end
		if not sync_code and g_Combat:IsLocalPlayerEndTurn() or --this is async
			sync_code and not IsNetPlayerTurn() then --this is sync
			return false, "not_local_turn"
		end
	end

	return true
end

function Unit:TunnelBlock(tunnel_entrance, tunnel_exit)
	for i, o in ipairs(self.tunnel_blockers) do
		if o.tunnel_end_point == tunnel_exit and tunnel_entrance:Equal(o:GetPosXYZ()) then
			return
		end
	end
	local o = PlaceObject("TunnelBlocker")
	o.owner = self
	o.tunnel_end_point = tunnel_exit
	pf.SetCollisionRadius(o, self:GetCollisionRadius())
	o:SetPos(tunnel_entrance)
	if not self.tunnel_blockers then
		self.tunnel_blockers = {}
	end
	table.insert(self.tunnel_blockers, o)
	if not (g_Combat and self:IsAware()) then
		MapForEach(tunnel_exit, 0, "Unit", function(o, self)
			if o:GetEnumFlags(const.efResting) == 0 or o:IsDead() then
				return
			end
			if o.command == "Idle" and o ~= self then
				o:SetCommand("GotoSlab", tunnel_exit)
			end
		end, self)
	end
end

function Unit:TunnelUnblock(tunnel_entrance, tunnel_exit)
	for i, o in ipairs(self.tunnel_blockers) do
		if o.tunnel_end_point == tunnel_exit and tunnel_entrance:Equal(o:GetPosXYZ()) then
			table.remove(self.tunnel_blockers, i)
			DoneObject(o)
			break
		end
	end
end

function Unit:TunnelsUnblock()
	local list = self.tunnel_blockers
	if not list or #list == 0 then
		return
	end
	for i, o in ipairs(list) do
		DoneObject(o)
	end
	table.iclear(list)
end

local function CheckInterruptCombatGotoPos(x, y, z, unit, ignore_pos)
	if not CanOccupy(unit, x, y, z) then
		return false
	end
	if ignore_pos and ignore_pos:Equal(x, y, z) then
		return false
	end
	local cost = unit.combat_path_obj:GetAP(point_pack(x, y, z))
	if not cost or cost >= (unit.combat_path_obj:GetAP(unit.combat_path[1]) or 0) then
		return false
	end
	return true
end

function Unit:GetInterruptCombatPath()
	local path = self.combat_path
	if not path or #path == 0 then
		return
	end
	local idx = #path
	local cur_pos
	if self.traverse_tunnel then
		cur_pos = point(point_unpack(path[idx]))
		idx = idx - 1
	else
		cur_pos = self:GetVisualPos()
		if not self:IsValidZ() then
			cur_pos = cur_pos:SetInvalidZ()
		end
	end
	for i = idx, 1, -1 do
		local x, y, z = point_unpack(path[i])
		local next_pos = point(x, y, z)
		local back_pos
		if i == idx and not self.traverse_tunnel then
			local pass_pos = GetPassSlab(self)
			if pass_pos and pass_pos ~= cur_pos then
				local a1 = CalcOrientation(cur_pos, next_pos)
				local a2 = CalcOrientation(cur_pos, pass_pos)
				if abs(AngleDiff(a1, a2)) > 90 * 60 then
					back_pos = pass_pos
				end
			end
		end
		local interrupt_pos
		if cur_pos ~= next_pos and not pf.GetTunnel(cur_pos, next_pos) then
			interrupt_pos = RasterizeSegmentPassSlabs(cur_pos, next_pos, CheckInterruptCombatGotoPos, self, back_pos)
		elseif SnapToVoxel(next_pos) == next_pos and CheckInterruptCombatGotoPos(x, y, z, self, back_pos) then
			interrupt_pos = next_pos
		end
		if interrupt_pos then
			if i == 1 and interrupt_pos == next_pos then
				return
			end
			local new_path = { point_pack(interrupt_pos) }
			for j = i + 1, #path do
				table.insert(new_path, path[j])
			end
			return new_path
		end
		cur_pos = next_pos
	end
end

function Unit:CombatGotoInterrupt(new_pos, restore_ap_only)
	if not self.combat_path or not self.combat_path_obj or self:IsDead() then
		return
	end
	local prev_pos = self.combat_path[1]
	local prev_cost = self.combat_path_obj:GetAP(prev_pos) or 0

	local interrupt_path
	if new_pos then
		if IsPoint(new_pos) then
			new_pos = point_pack(new_pos)
		end
		interrupt_path = { new_pos }
	else
		interrupt_path = self:GetInterruptCombatPath()
		if not interrupt_path then
			return
		end
		new_pos = interrupt_path[1]
	end
	local new_cost = self.combat_path_obj:GetAP(new_pos) or 0
	self.combat_path_obj = false
	self.combat_path = false
	if new_cost < prev_cost then
		self:GainAP(prev_cost - new_cost)
		if self.start_move_free_ap > 0 then
			-- restore ap -> free move ap
			local start_ui_ap = self.start_move_total_ap - self.start_move_free_ap
			self.free_move_ap = Max(0, self.ActionPoints - start_ui_ap)
			ObjModified(self)
		end
	end
	if restore_ap_only then
		return
	end
	SetCombatActionState(self, false)
	RunCombatAction("Move", self, new_cost, { goto_pos = point(point_unpack(new_pos)), path = interrupt_path })
end

local function ForEachWalkStep(p0, p1, f, ...)
	local step = const.SlabSizeX
	local x0, y0, z0 = p0:xyz()
	local x1, y1, z1 = p1:xyz()
	local dx = x1 - x0
	local dy = y1 - y0
	if abs(dx) >= abs(dy) then
		local step = step * (x1 >= x0 and 1 or -1)
		for x = x0 + step, x1, step do
			local y = y0 + MulDivRound(x - x0, dy, dx)
			f(point(x, y, z0), ...)
		end
	else
		local step = step * (y1 >= y0 and 1 or -1)
		for y = y0 + step, y1, step do
			local x = x0 + MulDivRound(y - y0, dx, dy)
			f(point(x, y, z0), ...)
		end
	end
end

function Unit:CanQuickPlayInCombat(noQuickPlay)
	return g_Combat and not noQuickPlay and not self.visible and self.team and not self.team.player_team
end

local function IsSamePos(p1, p2)
	if not p1 ~= not p2 then return false end
	local x1, y1, z1 = p1:xyz()
	local x2, y2, z2 = p2:xyz()
	z1 = z1 or terrain.GetHeight(x1, y1)
	z2 = z2 or terrain.GetHeight(x2, y2)
	return (x1 == x2) and (y1 == y2) and (z1 == z2)
end

function Unit:CombatGoto(action_id, cost_ap, pos, interrupt_path, forced_run, stanceAtStart, stanceAtEnd, fallbackMoveTracking, visibleMovement)
	Msg("UnitAnyMovementStart", self, pos, stanceAtStart, stanceAtEnd)
	
	self:RemovePreparedAttackVisuals()
	if interrupt_path then
		self.combat_path = interrupt_path
		pos = point(point_unpack(interrupt_path[1]))
	else
		self.combat_path_obj = GetCombatPath(self, stanceAtStart, cost_ap, stanceAtEnd)
		self.combat_path = self.combat_path_obj:GetCombatPathFromPos(pos)
		
		if not stanceAtStart and self.combat_path and self.combat_path_obj.destination_stances and pos then
			stanceAtStart = self.combat_path_obj.destination_stances[point_pack(pos)]
		end
		
		local new_cost = self.combat_path_obj:GetAP(pos)
		if not new_cost or new_cost > cost_ap then
			self:GainAP(cost_ap)
			CombatActionInterruped(self)
			return false
		end
		if new_cost < cost_ap then
			self:GainAP(cost_ap - new_cost)
			cost_ap = new_cost
		end
	end
	if not self.combat_path then
		self:GainAP(cost_ap)
		return true
	end
	if self.combat_path_obj then
		self:SetActionInterruptCallback("CombatGotoInterrupt")
	end
	local thread_RunStop
	self:PushDestructor(function(self)
		DeleteThread(thread_RunStop)
		if IsValid(self) then
			if self.combat_path then
				self:CombatGotoInterrupt(nil, "restore_ap_only")
			end
			self:SetActionInterruptCallback()
		end
		self.combat_path_obj = false
		self.combat_path = false
		self.in_combat_movement = false
	end)
	self.in_combat_movement = true

	if stanceAtStart and self.stance ~= stanceAtStart then
		self:ChangeStance("Stance" .. stanceAtStart, 0, stanceAtStart)
	end

	-- update move anim
	local path = self.combat_path
	local pfclass = self:GetPfClass() + 1
	local tunnel_mask = pathfind[pfclass].tunnel_mask
	local GetTunnel = pf.GetTunnel
	local run_dist = 0
	local px, py, pz = self:GetPosXYZ()
	for i = #path, 1, -1 do
		if terrain.GetPassType(px, py, pz) == pathfind_water_pass_type_idx then
			break
		end
		local px2, py2, pz2 = point_unpack(path[i])
		local tunnel = GetTunnel(px, py, pz, px2, py2, pz2, tunnel_mask)
		if tunnel and not tunnel:CanSprintThrough() then
			break
		end
		run_dist = run_dist + GetLen(px - px2, py - py2, pz and pz2 and pz - pz2 or 0)
		px, py, pz = px2, py2, pz2
	end

	local move_anim_type
	if self.species == "Human" then
		if self.stance == "Standing" and (forced_run or run_dist >= 5 * const.SlabSizeX) then
			move_anim_type = "Run"
		end
	end

	local has_closed_door = false
	local px, py, pz = self:GetPosXYZ()
	local closed_door_mask = const.TunnelMaskClosedDoor
	for i = #path, 1, -1 do
		local px2, py2, pz2 = point_unpack(path[i])
		local tunnel = GetTunnel(px, py, pz, px2, py2, pz2, closed_door_mask)
		if tunnel then
			has_closed_door = true
			break
		end
		px, py, pz = px2, py2, pz2
	end

	self:SetIK("AimIK", false)
	self:SetFootPlant(true)
	local base_idle = self:GetIdleBaseAnim()
	local goto_dummies = self:GenerateTargetDummiesFromPath(self.combat_path)
	for _, dummy in ipairs(goto_dummies) do
		if dummy.insert_idx then
			dummy.insert_before_pos = self.combat_path[dummy.insert_idx] or "limit"
		end
	end

	local known_traps
	local all_move_interrupts = self:CheckProvokeOpportunityAttacks(CombatActions.Move, "move", goto_dummies, true, "all")
	for i, t in ipairs(all_move_interrupts) do
		if t[1] == "trap" then
			known_traps = known_traps or {}
			table.insert(known_traps, t[2])
		end
	end

	local provoke_idx, provoke_pos, interrupts
	local UpdateProvokePos = function(init)
		if provoke_idx then
			for i = 1, provoke_idx do
				table.remove(goto_dummies, 1)
			end
		elseif not init then
			return
		end
		interrupts, provoke_idx = self:CheckProvokeOpportunityAttacks(CombatActions.Move, "move", goto_dummies, nil, nil, nil, known_traps)
		provoke_pos = provoke_idx and goto_dummies[provoke_idx].pos
		if provoke_pos then
			-- add the provoke point in the path if not present
			local insert_idx
			local insert_marker = goto_dummies[provoke_idx].insert_before_pos
			if insert_marker == "limit" then
				insert_idx = #path + 1
			else
				local pp = point_pack(provoke_pos)
				local provoke_dist = self:GetDist(provoke_pos)
				for i, ppos in ipairs(path) do
					if ppos == pp then
						insert_idx = false
						break
					elseif insert_marker == ppos or (self:GetDist(point_unpack(ppos)) < provoke_dist) then
						insert_idx = i
						break
					end
				end
			end
			
			if insert_idx then
				table.insert(path, insert_idx, point_pack(provoke_pos))
			end
			return
		end
		local goto_pos, angle
		if not next(self.combat_path)  then
			goto_pos = self:GetPos()
		else
			goto_pos = point(point_unpack(self.combat_path[1]))
			if self.combat_path[2] then
				angle = CalcOrientation(point(point_unpack(self.combat_path[2])), goto_pos)
			end
		end
		angle = angle or self:GetOrientationAngle()
		self:SetTargetDummy(goto_pos, angle, base_idle, 0)
		self.target_dummy:SetEnumFlags(const.efResting)
		-- update occupy in advance to allow parallel unit movements
		if action_id and not has_closed_door and CombatActions[action_id].SimultaneousPlay and not fallbackMoveTracking then
			SetCombatActionState(self, "PostAction")
		end
	end
	UpdateProvokePos(true)
	if provoke_pos then
		self:SetTargetDummy(false)
		if self.command ~= "Reposition" then
			WaitOtherCombatActionsEnd(self)
		end
	end

	-- If was visible at the start of movement, should be visible throughout
	local povTeam = GetPoVTeam()
	if povTeam then
		if HasVisibilityTo(povTeam, self) then
			self.visibility_override = goto_dummies[1]
		end
	end

	-- If will enter overwatch, show me as if there.
	if not self.visibility_override then
		for i, int in ipairs(interrupts) do
			if int[1] == "overwatch" then
				self.visibility_override = goto_dummies[provoke_idx]
			end
		end
	end

	-- Update visibility as if at final pos otherwise.
	if not self.visibility_override then
		self.visibility_override = goto_dummies[#goto_dummies]
	end

	if self.command == "CombatGoto" and self:IsLocalPlayerControlled() then
		if not self:HasStatusEffect("Panicked") and not self:HasStatusEffect("Berserk") then
			local distanceMove = GetCombatPathLen(path, self)
			if distanceMove >= const.SlabSizeX * 3 then
				if self:HasStatusEffect("Hidden") then
					PlayVoiceResponse(self, "CombatMovementStealth")
				else
					PlayVoiceResponse(self, "CombatMovement")
				end
			end
		end
	end

	local cur_pos = GetPassSlab(self) or self:GetVisualPos()
	if provoke_pos then
		self:SetTargetDummy(false) -- the target used for opportunity attacks
		if IsSamePos(provoke_pos, cur_pos) then
			self:ProvokeOpportunityAttacksFromList(interrupts)
			UpdateProvokePos()
		end
	end

	local next_pos_idx = #path
	if self:GetDist2D(point_unpack(path[next_pos_idx])) == 0 then
		next_pos_idx = next_pos_idx - 1
		if next_pos_idx > 0 and not IsValidPos(point_unpack(path[next_pos_idx])) then
			next_pos_idx = next_pos_idx - 1 -- skip tunnel marker
		end
	end
	local next_pt = next_pos_idx > 0 and point(point_unpack(path[next_pos_idx]))
	self:ClearEnumFlags(const.efResting)
	self:UpdateMoveAnim(action_id, move_anim_type, next_pt)
	local start_angle = next_pt and CalcOrientation(self, next_pt)
	local move_anim = GetStateName(self:GetMoveAnim())
	self:ReturnToCover(nil, false) -- do not touch the target dummy
	self:PlayTransitionAnims(move_anim, start_angle)
	self:GotoTurnOnPlace(next_pt)

	VisibilityUpdate()
	self:StartMoving()

	-- follow path
	local prev_pos = cur_pos
	Msg("UnitMovementStart", self, cur_pos)
	local stop_anim_pos = self:CombatGoto_GetStopAnimPos()
	local play_stop_dist
	while true do
		self:UpdateMoveSpeed()
		self:UpdateInWaterFX()
		if IsSamePos(provoke_pos, cur_pos) then
			self:ProvokeOpportunityAttacksFromList(interrupts)
			UpdateProvokePos()
		end
		local next_pos = point(point_unpack(path[#path]))
		if next_pos == cur_pos then
			path[#path] = nil
			if #path == 0 then
				break
			end
			next_pos = point(point_unpack(path[#path]))
		end
		local quick_play = self:CanQuickPlayInCombat(visibleMovement)
		if cur_pos == stop_anim_pos and not provoke_pos and not quick_play then
			play_stop_dist = self:StartPlayRunStop(path)
		end
		if play_stop_dist then
			local anim = self:GetStateText()
			local has_end_phase, end_phase = self:IterateMoments(anim, 0, 1, "end")
			if not has_end_phase then
				end_phase = GetAnimDuration(self:GetEntity(), anim) - 1
			end
			if not thread_RunStop then
				thread_RunStop = CreateGameTimeThread(function(self, pos, end_phase)
					local has_hit_phase, hit_phase = self:IterateMoments(anim, 0, 1, "hit")
					if not has_hit_phase then
						hit_phase = end_phase
					end
					local next_hit_time = self:TimeToPhase(1, hit_phase)
					if next_hit_time then
						Sleep(next_hit_time)
					end
					local surface_fx_type, surface_pos = GetObjMaterial(pos:IsValidZ() and pos or pos:SetTerrainZ())
					PlayFX("RunStop", "hit", self, surface_fx_type, surface_pos)
				end, self, next_pos, end_phase)
			end
			local next_pos_time
			if #path == 1 then
				next_pos_time = self:TimeToPhase(1, end_phase)
			else
				local phase = self:GetAnimPhase(1)
				local next_step_dist = self:GetStepVector(anim, 0, phase, end_phase - phase):Len2D() * self:GetVisualDist2D(next_pos) / play_stop_dist
				local min = phase
				local max = end_phase
				while max - min > 10 do
					local m = min + (max - min) / 2
					local len = self:GetStepVector(anim, 0, phase, m - phase):Len2D()
					if len < next_step_dist then
						min = m
					else
						max = m
					end
				end
				next_pos_time = self:TimeToPhase(1, min)
			end
			self:SetPos(next_pos, next_pos_time or 0)
			if next_pos_time then
				Sleep(next_pos_time)
			end
			if #path == 1 then
				local surface_fx_type, surface_pos = GetObjMaterial(next_pos:IsValidZ() and next_pos or next_pos:SetTerrainZ())
				PlayFX("RunStop", "end", self, surface_fx_type, surface_pos)
			end
		else
			local tunnel = GetTunnel(cur_pos, next_pos, tunnel_mask)
			if tunnel then
				local can_use_tunnel
				can_use_tunnel, quick_play = self:InteractTunnel(tunnel, quick_play)
				if not can_use_tunnel then
					self:Interrupt(nil, cur_pos) -- locked door
					break
				end
				if not IsValid(tunnel) then
					-- the open door erased the tunnel
					tunnel = GetTunnel(cur_pos, next_pos, tunnel_mask)
				end
				if tunnel then
					self:TraverseTunnel(tunnel, cur_pos, next_pos, false, quick_play)
					if quick_play and self:GetStateText() ~= move_anim then
						self:SetState(move_anim, const.eKeepComponentTargets, 0)
					end
				elseif IsPassSlabStep(cur_pos, next_pos, 0, self:GetPfClass()) then
					next_pos = cur_pos
				else
					self:Interrupt() -- the path is no more valid
					break
				end
			else
				if self:GetStateText() ~= move_anim then
					self:SetState(move_anim, const.eKeepComponentTargets, quick_play and 0 or -1)
					self:SetFootPlant(true)
				end
				local angle = CalcOrientation(cur_pos, next_pos)
				local max_step_len = 5 * const.SlabSizeX
				local step_dist = cur_pos:Dist2D(next_pos)
				if step_dist > max_step_len then
					table.insert(path, point_pack(next_pos))
					next_pos = RotateRadius(max_step_len, angle, cur_pos)
					step_dist = cur_pos:Dist2D(next_pos)
				end
				if quick_play then
					self:SetPos(next_pos)
					self:SetOrientationAngle(angle)
				else
					while step_dist > 0 do
						local time = MulDivRound(step_dist, 1000, Max(1, self:GetSpeed()))
						self:SetPos(next_pos, time)
						if self.ground_orient then
							local steps = 1 + step_dist / (const.SlabSizeX / 2)
							for i = 1, steps do
								local t = time * i / steps - time * (i-1) / steps
								self:SetOrientationAngle(angle, t)
								if WaitWakeup(t) then
									break
								end
							end
						else
							self:SetOrientationAngle(angle, 300)
							WaitWakeup(time)
						end
						step_dist = self:GetVisualDist2D(next_pos)
					end
				end
			end
		end
		cur_pos = next_pos
		Msg("CombatGotoStep", self)
	end
	
	if stanceAtEnd and self.stance ~= stanceAtEnd then
		self:ChangeStance("Stance" .. stanceAtEnd, 0, stanceAtEnd)
	end

	self.combat_path_obj = false
	self.combat_path = false
	self:PopAndCallDestructor()
	Msg("UnitMovementDone", self, action_id, prev_pos)
	return true
end

function Unit:CombatGoto_GetStopAnimPos()
	if self.species ~= "Human" or self.stance == "Prone" or self.infected then
		return
	end
	local path = self.combat_path
	local pfclass = self:GetPfClass() + 1
	local tunnel_mask = pathfind[pfclass].tunnel_mask
	if path[#path] ~= point_pack(self:GetPosXYZ()) then
		table.insert(path, point_pack(self:GetPos()))
	end
	if #path < 2 then
		return
	end
	local p1 = point(point_unpack(path[1]))
	local p2 = point(point_unpack(path[2]))
	local tunnel = pf.GetTunnel(p2, p1, tunnel_mask)
	if tunnel then
		local tunnel_type = pf.GetTunnelType(tunnel)
		if tunnel_type ~= (tunnel_type & const.TunnelMaskWalk) then
			return
		end
	end
	local dir_pos = RotateRadius(const.SlabSizeX, CalcOrientation(p2, p1), p1)
	if GetCoverFrom(p1, dir_pos) == 0 then
		return -- there should be a cover ahead of us
	end

	local move_anim = GetStateName(self:GetMoveAnim())
	local is_running = string.match(move_anim, ".*_CombatRun.*") and true or false
	local stop_distance, min_stop_distance
	if is_running then
		stop_distance = 5*guim
		min_stop_distance = stop_distance
	else
		stop_distance = 2*guim
		min_stop_distance = stop_distance
	end

	local start_stop_anim_pos = p1
	local start_stop_anim_idx = 1
	for i = 2, #path do
		local prev = point(point_unpack(path[i]))
		local tunnel = pf.GetTunnel(prev, start_stop_anim_pos, tunnel_mask)
		if tunnel then
			local tunnel_type = pf.GetTunnelType(tunnel)
			if tunnel_type ~= (tunnel_type & const.TunnelMaskWalk) then
				break
			end
		end
		if i > 2 and DistSegmentToPt2D(p1, p2, prev) >= 2 then
			break
		end
		start_stop_anim_pos = prev
		start_stop_anim_idx = i
		if not IsCloser2D(p1, start_stop_anim_pos, stop_distance) then
			break
		end
	end
	if IsCloser2D(p1, start_stop_anim_pos, min_stop_distance) then
		return
	end
	if not IsCloser2D(p1, start_stop_anim_pos, stop_distance) then
		if p1:IsValidZ() or start_stop_anim_pos:IsValidZ() then
			if not p1:IsValidZ() then p1 = p1:SetTerrainZ() end
			if not start_stop_anim_pos:IsValidZ() then start_stop_anim_pos = start_stop_anim_pos:SetTerrainZ() end
		end
		start_stop_anim_pos = p1 + SetLen(start_stop_anim_pos - p1, stop_distance)
		table.insert(path, start_stop_anim_idx, point_pack(start_stop_anim_pos))
	end
	return start_stop_anim_pos
end

function Unit:StartPlayRunStop(path)
	local move_anim = GetStateName(self:GetMoveAnim())
	local stop_anim = string.match(move_anim, "(.*_Combat%a*).*")
	if stop_anim then
		stop_anim = self:GetRandomAnim(stop_anim .. "Stop")
	end
	if not stop_anim or not IsValidAnim(self, stop_anim) then
		return false
	end

	local moments = self:GetAnimMoments(stop_anim)
	moments = table.ifilter(moments, function(_, m) return m.Type == "FootLeft" or m.Type == "FootRight" end)
	if #moments == 0 then
		print("once", string.format('missing "FootLeft" and "FootRight" moments in anim %s for %s (%s)', stop_anim, self.unitdatadef_id, self:GetEntity()))
	end

	local cur_anim = GetStateName(self:GetAnim(1))
	local cur_phase = self:GetAnimPhase(1)
	local has_moment1, t1 = self:IterateMoments(cur_anim, cur_phase, 1, "FootLeft", false, true)
	local has_moment2, t2 = self:IterateMoments(cur_anim, cur_phase, 1, "FootRight", false, true)
	if not has_moment1 or not has_moment2 then
		t1 = false
		t2 = false
	end

	local next_moment_type, prc
	if not t1 or not t2 or t1 == t2 or #moments < 2 then
		prc = 0
	elseif t1 < t2 then
		next_moment_type = "FootLeft"
		prc = MulDivRound(t1, 1000, t2 - t1)
	else
		next_moment_type = "FootRight"
		prc = MulDivRound(t2, 1000, t1 - t2)
	end

	local dist_to_stop = 0
	local stop_pos = self:GetPos()
	for i = #path, 1, -1 do
		local p2 = point(point_unpack(path[i]))
		dist_to_stop = dist_to_stop + stop_pos:Dist2D(p2)
		stop_pos = p2
	end
	local duration = GetAnimDuration(self:GetEntity(), stop_anim)
	local start_idx = (not next_moment_type or moments[1].Type == next_moment_type) and 1 or 2
	local step = next_moment_type and 2 or 1
	local best_phase, best_value
	for i = start_idx, #moments, step do
		local phase = moments[i].Time
		if prc > 0 then
			local d = i == 1 and moments[2].Time - phase or phase - moments[i-1].Time
			phase = phase - MulDivRound(d, prc, 1000)
		end
		if phase >= 0 then
			local len = self:GetStepVector(stop_anim, 0, phase, duration - phase):Len2D()
			local value = abs(len - dist_to_stop)
			if not best_value or value < best_value then
				best_phase = phase
				best_value = value
			end
		end
	end
	self:SetAnimChannel(1, stop_anim, 0, -1, 100, const.StopAnimCrossfadeTime)
	self:SetAnimPhase(1, best_phase or 0)
	self:Face(stop_pos, 200)
	return dist_to_stop
end

function Unit:Teleport(pos, angle)
	self:LeaveEmplacement(true)
	self:HolsterBombardWeapon()
	self.return_pos = false
	if not pos then
		pos = pos or GetPassSlab(self) or SnapToVoxel(self:GetPos())
	end
	self:SetPos(pos)
	if self:IsDead() then
		self:SetFootPlant(true, 0)
	else
		Msg("UnitAnyMovementStart", self)
		local orientation_angle = self:GetPosOrientation(pos, angle, self.stance, true, true)
		local base_idle = self:GetIdleBaseAnim()
		self:SetRandomAnim(base_idle, 0, 0, true)
		self:SetOrientationAngle(orientation_angle, 0)
		self:SetFootPlant(true, 0)
		self:SetTargetDummy(pos, orientation_angle, base_idle, 0)
		CombatPathReset(self)
		self:ProvokeOpportunityAttacks(CombatActions.Move, "move")
		Msg("UnitMovementDone", self)
		RedeploymentCheckDelayed()
	end
end

function Unit:UpdateMoveAnimFromStyle(move_style_id, next_pt)
	move_style_id = move_style_id or self.cur_move_style
	local move_style = GetAnimationStyle(self, move_style_id)
	if not move_style then
		return false
	end
	local anim, rotation_time
	if self:GetStepLength() == 0 then
		if next_pt and (move_style.MoveStart_Left or "") ~= "" and (move_style.MoveStart_Right or "") ~= "" then
			local start_angle = self:GetVisualOrientationAngle()
			local angle = CalcOrientation(self, next_pt)
			local angle_diff = AngleDiff(angle, start_angle)
			if abs(angle_diff) >= 30*60 then
				local rotate_anim = angle_diff < 0 and move_style.MoveStart_Left or move_style.MoveStart_Right
				if rotate_anim and IsValidAnim(self, rotate_anim) then
					anim = rotate_anim
					rotation_time = GetAnimDuration(self:GetEntity(), anim)
				end
			end
		end
		if not anim and move_style.MoveStart and IsValidAnim(self, move_style.MoveStart) then
			anim = move_style.MoveStart
		end
	end
	if not anim then
		anim = self:GetStateText()
		if self:GetAnimPhase() == 0 or self:IsAnimEnd() or not move_style:HasMoveAnim(anim) then
			anim = move_style:GetRandomMoveAnim(self)
			if not anim or not IsValidAnim(self, anim) then
				local msg = string.format('Missing animation style "%s - %s" animation "%s". Gender: "%s". Entity: "%s". Appearance: %s', move_style.group, move_style.Name, anim or "", self.gender, self:GetEntity(), self.Appearance or "false")
				StoreErrorSource(self, msg)
				return false
			end
		end
	end
	if self:GetStepLength(anim) == 0 then
		local msg = string.format('Animation step is ziro! animation "%s". Entity: "%s"', anim or "", self:GetEntity())
		StoreErrorSource(self, msg)
		return false
	end
	self:SetMoveAnim(anim)
	self:SetRotationTime(rotation_time or 0)
	self:SetMoveTurnAnim(nil, nil)
	self:ChangePathFlags(const.pfAnimEnd)
	if (move_style.StepFX or "") ~= "" then
		self.move_step_fx = move_style.StepFX
	else
		if string.match(move_style.VariationGroup, "Run") then
			self.move_step_fx = "StepRun"
		else
			self.move_step_fx = "StepWalk"
		end
	end
	self.move_stop_anim_len = 0
	self.move_stop_foot_left_anim = false
	self.move_stop_foot_right_anim = false
	if (move_style.MoveStop_FootLeft or "") ~= "" and IsValidAnim(self, move_style.MoveStop_FootLeft) then
		self.move_stop_anim_len = self:GetStepLength(move_style.MoveStop_FootLeft)
		self.move_stop_foot_left_anim = move_style.MoveStop_FootLeft
		if (move_style.MoveStop_FootRight or "") ~= "" and IsValidAnim(self, move_style.MoveStop_FootRight) then
			self.move_stop_foot_right_anim = move_style.MoveStop_FootRight
		else
			self.move_stop_foot_right_anim = self.move_stop_foot_left_anim
		end
	end
	return true
end

function Unit:UpdateMoveAnim(action_id, anim_type, next_pt)
	if IsRealTimeThread() then
		--this func does interact rands
		--it is called in a rt when loading session data due to cascade onsetwhatevers
		--seems safe to ignore such calls, in fact it also asserts when called like that ->
		--turn_l and turn_r remain nil when move_anim doesn't
		return
	end
	NetUpdateHash("Unit:UpdateMoveAnim", action_id, anim_type, next_pt)
	local use_combat_anims
	self.cur_move_style = false
	if g_Combat and self:IsAware() then
		use_combat_anims = true
	elseif self.species == "Human" then
		local move_style = self:GetCommandParam("move_style")
		if not move_style then
			if self:IsVisiting() then
				move_style = self:GetDefaultMoveStyle()
			elseif not move_style and const.MercWalkStyle and self:IsMerc() then
				move_style = const.MercWalkStyle
				if type(move_style) ~= "string" or not GetAnimationStyle(self, move_style) then
					move_style = self:GetDefaultMoveStyle()
				end
			end
		end
		if move_style and self:UpdateMoveAnimFromStyle(move_style, next_pt) then
			self.cur_move_style = move_style
		end
	end
	NetUpdateHash("Unit:UpdateMoveAnim01", self.cur_move_style)
	if not self.cur_move_style or self.carry_flare then
		self:ChangePathFlags(0, const.pfAnimEnd)
		-- anim_type can be: Run, Walk, WalkSlow
		anim_type = anim_type or self:GetCommandParam("move_anim")
		local move_anim, turn_l, turn_r
		if self.species ~= "Human" then
			if anim_type ~= "Run" and use_combat_anims and g_Combat then
				anim_type = "Run"
			end
			move_anim = anim_type == "Run" and "run" or "walk"
			if IsValidAnim(self, move_anim) then
				NetUpdateHash("Unit:UpdateMoveAnim0", move_anim)
				move_anim = self:GetRandomAnim(move_anim)
			end
			if self.species == "Crocodile" or self.species == "Hyena" then
				if anim_type == "Run" then
					turn_l, turn_r = "run_Turn_L", "run_Turn_R"
				else
					turn_l, turn_r = "walk_Turn_L", "walk_Turn_R"
				end
			end
		elseif self.carry_flare then
			move_anim = "nw_Standing_Patrol_Flare"
			anim_type = "Walk"
		elseif use_combat_anims then
			local prefix = self:GetWeaponAnimPrefix()
			if action_id == "Charge" and prefix == "mk_" then
				local weapon, weapon2 = self:GetActiveWeapons()
				if IsKindOf(weapon, "MacheteWeapon") then
					move_anim = "mk_Standing_Machete_Run"
					anim_type = "Run"
				end
			end
			if not move_anim or not IsValidAnim(self, move_anim) then
				if self.stance == "Standing" then
					if anim_type == "Run" then
						move_anim = string.format("%sStanding_CombatRun", prefix)
					elseif anim_type == "Walk" or anim_type == "WalkSlow" then
						move_anim = string.format("%sStanding_CombatWalk", prefix)
					end
				elseif self.stance == "Crouch" then
					move_anim = string.format("%sStanding_CombatWalk", prefix)
					anim_type = "Walk"
				end
			end
			if move_anim and IsValidAnim(self, move_anim) then
				local cur_anim = self:GetStateText()
				NetUpdateHash("Unit:UpdateMoveAnim1", cur_anim, move_anim, IsAnimVariant(cur_anim, move_anim))
				move_anim = IsAnimVariant(cur_anim, move_anim) and cur_anim or self:GetRandomAnim(move_anim)
			end
		end
		if not move_anim or not IsValidAnim(self, move_anim) then
			local default_walk_style = (use_combat_anims or IsMerc(self) or self.stance ~= "Standing") and "Run" or "Walk"
			if not anim_type or (anim_type == "Walk" or anim_type == "WalkSlow") and self.stance ~= "Standing" then
				anim_type = default_walk_style
			end
			move_anim = self:GetActionBaseAnim(anim_type or default_walk_style, self.stance)
			if not move_anim and anim_type ~= default_walk_style then
				move_anim = self:GetActionBaseAnim(default_walk_style, "Standing")
			end
			if move_anim and (not self.behavior or RandomWalkAnimBehaviors[self.behavior]) then
				local cur_anim = self:GetStateText()
				NetUpdateHash("Unit:UpdateMoveAnim1", cur_anim, move_anim, IsAnimVariant(cur_anim, move_anim))
				move_anim = IsAnimVariant(cur_anim, move_anim) and cur_anim or self:GetRandomAnim(move_anim)
			end
		end
		self.move_step_fx =
			self.stance == "Prone" and "StepRunProne" or
			self.stance == "Crouch" and "StepRunCrouch" or
			anim_type == "Run" and "StepRun" or "StepWalk"
		local base_idle = self:GetIdleBaseAnim()
		self:SetMoveAnim(move_anim or self:GetIdleBaseAnim())
		self:SetRotationTime(0)
		self:SetMoveTurnAnim(turn_l, turn_r)
	end
	self:SetWaitAnim(self:GetIdleBaseAnim())
	self:UpdateMoveSpeed()
	self:UpdatePFClass()
end

function Unit:GetDefaultMoveStyle()
	if self.carry_flare then
		return GetRandomAnimationStyle(self, "Flare")
	end
	if not self.default_move_style then
		local style = self:GetRandomMoveStyle()
		if style then
			self.default_move_style = style.Name
		end
	end
	return self.default_move_style
end

function Unit:CalcMoveSpeedModifier()
	local modifier = 1000
	if terrain.GetPassType(self:GetVisualPosXYZ()) == pathfind_water_pass_type_idx then
		modifier = modifier + 10 * Presets.ConstDef["Action Point Costs"].WaterMoveSpeedModifier.value
	end
	if self:HasStatusEffect("Hidden") then 
		modifier = MulDivRound(modifier, 700, 1000)
	end
	local command_move_speed_modifier = self:GetCommandParam("move_speed_modifier")
	if command_move_speed_modifier then
		modifier = MulDivRound(modifier, command_move_speed_modifier, 1000)
	end
	return modifier
end

function Unit:UpdateMoveSpeed()
	local modifier = self:CalcMoveSpeedModifier()
	local speed
	if not g_Combat and self:IsMerc() then
		local move_anim = GetStateName(self:GetMoveAnim())
		local is_running = string.match(move_anim, ".*Run.*") and true or false
		if is_running then
			-- fixed speed for mercs
			if self.stance == "Standing" then
				speed = const.UnitMoveSpeed.MercStandingStance
			elseif self.stance == "Crouch" then
				speed = const.UnitMoveSpeed.MercCrouchStance
			elseif self.stance == "Prone" then
				speed = const.UnitMoveSpeed.MercProneStance
			end
		else
			if self.stance == "Standing" then
				speed = const.UnitMoveSpeed.MercWalk
			end
		end
	end
	if speed then
		local mod = MulDivRound(modifier, self:GetAnimSpeedModifier(), 1000)
		speed = MulDivRound(speed, mod, 1000)
		self:SetSpeed(speed)
	else
		self:SetMoveSpeed(modifier)
	end
	-- debug set speed on zero speed animations
	if self:GetSpeed() == 0 then
		self:SetSpeed(self.fallback_walk_speed)
	end
end

function Unit:UpdateInWaterFX()
	local fx_in_water = not self:IsDead() and terrain.GetPassType(self:GetVisualPosXYZ()) == pathfind_water_pass_type_idx
	if self.fx_in_water ~= fx_in_water then
		if fx_in_water then
			PlayFX("UnitInWater", "start", self)
		else
			PlayFX("UnitInWater", "end", self)
		end
		self.fx_in_water = fx_in_water
	end
end

function Unit:StartMoving()
	self.is_moving = true
	local team = self.team
	if not (team and team.neutral and EngineOptions.ObjectDetail == "Low") then
		PlaceUnitWindModifierTrail(self)
	end
end

function Unit:StopMoving()
	self.is_moving = false
	RemoveUnitWindModifierTrail(self)
end

function Unit:GetMovementNoise()
	local stance = self.species == "Human" and self.stance or "Standing"
	return Presets.CombatStance.Default[stance].Noise
end

function Unit:InteractTunnel(tunnel, quick_play)
	return tunnel:InteractTunnel(self, quick_play)
end

-- collision avoidance. offset pos2 to the right pass cell corner
function GetTunnelExitCollisionAvoidPos(pos1, pos2)
	local x1, y1, z1 = SnapToVoxel(pos1:xyz())
	local x2, y2, z2 = SnapToVoxel(pos2:xyz())
	if x1 == x2 and y1 == y2 then
		return pos2
	end
	local offset = const.SlabSizeX / 4
	if x1 == x2 then
		if y1 < y2 then
			x2 = x2 - offset
			--y2 = y2 - offset
		elseif y1 > y2 then
			x2 = x2 + offset - 1
			--y2 = y2 + offset - 1
		end
	elseif y1 == y2 then
		if x1 < x2 then
			--x2 = x2 - offset
			y2 = y2 + offset - 1
		elseif x1 > x2 then
			--x2 = x2 + offset - 1
			y2 = y2 - offset
		end
	elseif x1 < x2 then
		if y1 < y2 then
			x2 = x2 - offset
		elseif y1 > y2 then
			y2 = y2 + offset - 1
		end
	elseif x1 > x2 then
		if y1 > y2 then
			x2 = x2 + offset - 1
		elseif y1 < y2 then	
			y2 = y2 - offset
		end
	end
	if z2 then
		z2 = GetVoxelStepZ(x2, y2, z2)
	end
	return point(x2, y2, z2)
end

MapVar("__unit_step_target_dummies", {{phase = 0}})

function Unit:TraverseTunnel(tunnel, pos1, pos2, collision_avoidance, quick_play, use_stop_anim)
	local tunnel_entrance = tunnel:GetEntrance()
	local tunnel_exit = tunnel:GetExit()
	if not pos1 then
		pos1 = tunnel_entrance
	end
	if not pos2 then
		pos2 = tunnel_exit
	end
	-- check for a dead end way
	local dead_end
	if not g_Combat and (tunnel.tunnel_type & const.TunnelMaskWalk) == 0 then
		local side = self.team and self.team.side
		if side == "player1" or side == "player2" then
			local tunnel_mask = pathfind[self:GetPfClass() + 1].tunnel_mask
			local reverse_tunnel = pf.GetTunnel(tunnel_exit, tunnel_entrance, tunnel_mask)
			if not reverse_tunnel then
				if IsStuckedMercPos(self, pos2) then
					dead_end = true
					if self:IsInterruptable() then
						self:Interrupt()
						return
					end
				end
			end
		end
	end
	if collision_avoidance ~= false and self:GetPathFlags(const.pfmCollisionAvoidance) ~= 0 and terrain.IsPassable(pos2) then
		local pcount = self:GetPathPointCount()
		local next_pos = pcount > 1 and self:GetPathPoint(pcount - 1)
		if next_pos and next_pos:IsValid() and (tunnel.tunnel_type & const.TunnelTypeLadder) == 0 and not CanDestlock(pos2, 300) then
			pos2 = GetTunnelExitCollisionAvoidPos(pos1, pos2) -- offset pos2 to the right pass cell corner
			pf.SetPathPoint(self, -1, pos2) -- the path execution expects the unit to be at the last position of the path
		end
	end
	local interrupts
	if not self.combat_path and self.team and self.team.side ~= "neutral" then
		local target_dummy = __unit_step_target_dummies[1]
		target_dummy.obj = self
		target_dummy.anim = self:GetWaitAnim()
		interrupts = self:CheckProvokeOpportunityAttacks(CombatActions.Move, "move", __unit_step_target_dummies)
		if interrupts then
			self:ProvokeOpportunityAttacksWarning("move", interrupts)
		end
	end
		local wasInterruptable = self.interruptable
		if wasInterruptable then
			self:EndInterruptableMovement()
		end
	if not quick_play and (tunnel.tunnel_type & const.TunnelMaskTraverseWait) ~= 0 then
		self:TunnelBlock(tunnel_entrance, tunnel_exit)
		self:TunnelBlock(tunnel_exit, tunnel_entrance)
	end
	self.traverse_tunnel = tunnel
	tunnel:TraverseTunnel(self, pos1, pos2, quick_play, use_stop_anim)
	self.traverse_tunnel = false
	if not quick_play and (tunnel.tunnel_type & const.TunnelMaskTraverseWait) ~= 0 then
		self:TunnelUnblock(tunnel_exit, tunnel_entrance)
		self:TunnelUnblock(tunnel_entrance, tunnel_exit)
	end
	self:SetFootPlant(true)
	if dead_end then
		RedeploymentCheckDelayed()
	end
	if wasInterruptable then
		self:BeginInterruptableMovement()
	end
	if interrupts then
		self:ProvokeOpportunityAttacksFromList(interrupts)
	end
end

function Unit:GotoStopCheck(stop_anim_tunnel_idx)
	if self.move_stop_anim_len == 0 then
		return false
	end
	if not stop_anim_tunnel_idx then
		stop_anim_tunnel_idx = pf.GetPathNextTunnelIdx(self, const.TunnelMaskWalkStopAnim) or 1
	end
	local pcount = self:GetPathPointCount()
	if pcount <= stop_anim_tunnel_idx + 4 then
		local pathlen = self:GetPathLen(stop_anim_tunnel_idx)
		local step_dist = self:GetVisualDist2D(self:GetPosXYZ()) 
		if pathlen - step_dist < self.move_stop_anim_len then
			local dest = self:GetPathPoint(stop_anim_tunnel_idx)
			if dest and not dest:IsValid() then
				stop_anim_tunnel_idx = stop_anim_tunnel_idx - 1
				dest = self:GetPathPoint(stop_anim_tunnel_idx)
			end
			if not dest or not dest:IsValid() then
				return false
			end
			-- clear path points before dest
			for i = self:GetPathPointCount(), stop_anim_tunnel_idx + 1, -1 do
				pf.SetPathPoint(self, i)
			end
			local wait_time = pathlen > self.move_stop_anim_len and pf.GetMoveTime(self, pathlen - self.move_stop_anim_len) or 0
			if wait_time > 0 then
				Sleep(wait_time)
			end
			self:GotoStop(dest)
			return true
		end
	end
	return false
end

function Unit:GotoStop(dest)
	local l1 = self:TimeToMoment(1, "FootLeft", -1)
	local l2 = self:TimeToMoment(1, "FootLeft", 1)
	local r1 = self:TimeToMoment(1, "FootRight", -1)
	local r2 = self:TimeToMoment(1, "FootRight", 1)
	local t1, t2, anim, anim1, anim2
	if l1 and (not r1 or l1 < r1) then
		t1, anim1 = l1, self.move_stop_foot_left_anim
	else
		t1, anim1 = r1, self.move_stop_foot_right_anim
	end
	if l2 and (not r2 or l2 < r2) then
		t2, anim2 = l2, self.move_stop_foot_left_anim
	else
		t2, anim2 = r2, self.move_stop_foot_right_anim
	end
	if t1 and t2 then
		local t = t1 + t2
		local perc = t > 0 and t1 * 100 / t or 0
		if perc < const.AmbientLife.WalkStopMomentProximity then
			anim = anim1
		else
			anim = anim2
		end
	elseif t1 then
		anim = anim1
	else
		anim = anim2
	end
	anim = anim or self.move_stop_foot_left_anim or self.move_stop_foot_right_anim
	self:SetState(anim)
	repeat
		self:SetAnimSpeed(1, self:GetMoveSpeed())
		local t = self:TimeToAnimEnd()
		self:SetPos(dest or self:GetPos(), t)
	until not WaitWakeup(t)
end

function Unit:MoveSleep(time)
	local end_time = now() + time
	repeat until not WaitWakeup(end_time - now()) or self:GetPathFlags(const.pfDirty) ~= 0
	if self.cur_move_style and (self:GetAnimPhase() == 0 or self:IsAnimEnd()) then
		self:UpdateMoveAnimFromStyle()
	end
end

function Unit:GotoTurnOnPlace(next_pos)
	if not next_pos then
		return
	end
	local move_style = GetAnimationStyle(self, self.cur_move_style)
	if move_style then
		if move_style.MoveStart_Left or move_style.MoveStart_Right then
			return -- move turn animations will be played if necessary
		end
		local angle = CalcOrientation(self, next_pos)
		self:AnimatedRotation(angle)
		return
	end
	if self:IsVisiting() then
		return -- move style support civilian
	end
	if self.stance ~= "Prone" then
		return
	end
	local angle = CalcOrientation(self, next_pos)
	local angle_diff = AngleDiff(angle, self:GetVisualOrientationAngle())
	local min_turn_angle
	if self:GetState() == self:GetMoveAnim() then
		min_turn_angle = const.GotoTurnOnPlaceMovingAngle
	else
		min_turn_angle = const.GotoTurnOnPlaceAngle
	end
	if abs(angle_diff) > min_turn_angle then
		self:AnimatedRotation(angle)
	end
end

DefineConstInt("AmbientLife", "ForbidVisitEnemyDist", 2, "m", "If player around this distance the enemy AL won't use chairs to sit(coming close will also interrupt this behavior normally)")

function Unit:IdleForcingDist(other)
	if self.waiting_attack then return true end
	
	local dist = self:GetDist(other)
	if dist <= const.AmbientLife.ForbidSitChairEnemyDist and IsSittingUnit(self) then
		return true
	end
	if dist <= const.AmbientLife.ForbidWallLeanEnemyDist and IsWallLeaningUnit(self) then
		return true
	end
	if dist <= const.AmbientLife.ForbidVisitEnemyDist and (self.routine == "Ambient" or self.routine == "Patrol") then
		return true
	end
end

function Unit:ShouldBeIdle(other)
	if self.command == "Die" or self.command == "Dead" then return false end
	
	if g_Combat or GameState.sync_loading or self.team and self.team.player_team then
		return true
	end
	if not g_Combat and (self.neutral_retal_attacked) then
		return true
	end
	if not IsValid(other) then
		local enemies = GetAllEnemyUnits(self)
		for _, unit in ipairs(enemies) do
			if self:ShouldBeIdle(unit) then
				return true
			end
		end
	else
		if self:IdleForcingDist(other) then
			return true
		end
	end
end

function Unit:GotoAction()
	if self.carry_flare then
		ResetVoxelStealthParamsCache() -- todo: partial invalidate would be cool (prev pos + current pos)
	end
	
	self:InvalidatePindownLinesCache()
	
	if not g_Combat and self:HasStatusEffect("Suspicious") then
		self:SetCommand("Idle")
		return
	end
	
	if self.goto_stance then
		self:GotoChangeStance(self.goto_stance)
		self.goto_stance = false
		if self:IsInterruptable() then
			self:BeginInterruptableMovement()
		end
	end
	if self.goto_hide then
		self.goto_hide = false
		self:Hide()
		if self:IsInterruptable() then
			self:BeginInterruptableMovement()
		end
	end	

	if self.team then
		local enemies = GetAllEnemyUnits(self)
		if self.team.player_team then	
			for _, unit in ipairs(enemies) do
				if unit:ShouldBeIdle(self) then
					unit:SetCommandParamValue("Idle", "idle_forcing_dist", self)
					unit:SetCommand("Idle")
				end
			end
		end
		if self.team.player_enemy then
			for _, unit in ipairs(enemies) do
				if self:ShouldBeIdle(unit) then
					self:SetCommandParamValue("Idle", "idle_forcing_dist", unit)
					self:SetCommand("Idle")
				end
			end
		end
		for _, enemy in ipairs(enemies) do
			local attacker, target
			if self.marked_target_attack_args and self.marked_target_attack_args.target == enemy then
				attacker, target = self, enemy
			elseif enemy.marked_target_attack_args and enemy.marked_target_attack_args.target == self then
				attacker, target = enemy, self
			end
			if attacker and target then
				local action = attacker:GetDefaultAttackAction()
				local weapon = action:GetAttackWeapons(attacker)
				if not IsKindOfClasses(weapon, "MeleeWeapon", "UnarmedWeapon") then
					attacker.marked_target_attack_args = nil
				elseif attacker:CanAttack(target, weapon, action) and IsMeleeRangeTarget(attacker, nil, nil, target) then
					local args = attacker.marked_target_attack_args
					TutorialHintsState.SneakMode = not not args
					TutorialHintsState.SneakApproach = not not args
					NetStartCombatAction(action.id, attacker, 0, args)
					break
				end
			end
		end
	end	
end

function Unit:WaitResumeOnCommandStart()
	if not GameTimeAdvanced then return end
	if IsValid(self.queued_action_visual) then
		DoneObject(self.queued_action_visual)
		self.queued_action_visual = false
	end
	if not g_Combat and IsActivePaused() and self:HasPreparedAttack() then
		self:InterruptPreparedAttack()
	end
	while not g_Combat and IsActivePaused() do
		WaitMsg("Resume", 500)
	end	
end

local pfFinished = const.pfFinished
local pfFailed = const.pfFailed
local pfDestLocked = const.pfDestLocked
local pfTunnel = const.pfTunnel
local gofRealTimeAnimMask = const.gofRealTimeAnim | const.gofEditorSelection

function Unit:GotoSlab(pos, distance, min_distance, move_anim_type, follow_target, use_stop_anim, interrupted)
	self:WaitResumeOnCommandStart()
	assert(self:GetGameFlags(gofRealTimeAnimMask) == 0)
	Msg("UnitAnyMovementStart", self)
	if use_stop_anim == nil then
		use_stop_anim = true
	end
	if use_stop_anim ~= false and self.move_stop_anim_len == 0 then
		use_stop_anim = false
	end

	self:SetTargetDummy(false)
	if self:TimeToPosInterpolationEnd() > 0 then
		local cur_pos = self:GetVisualPos()
		if not self:IsValidZ() then
			cur_pos = cur_pos:SetInvalidZ()
		end
		self:SetPos(cur_pos)
	end
	local dest, follow_pos
	if not pos and IsValid(follow_target) then
		dest = self:GetClosestMeleeRangePos(follow_target)
		follow_pos = follow_target:GetPos()
	elseif not pos then
		local tunnel_param = {
			unit = self,
			player_controlled = self.team and self.team:IsPlayerControlled(),
		}
		dest = GetCombatPathDestinations(self, nil, nil, nil, tunnel_param, nil, 2 * const.SlabSizeX, false, false, true)
		for i, packed_pos in ipairs(dest) do
			dest[i] = point(point_unpack(packed_pos))
		end
	elseif IsPoint(pos) then
		if self:GetPathFlags(const.pfmVoxelAligned) ~= 0 then
			dest = self:GetVoxelSnapPos(pos)
		end
	elseif self:GetPathFlags(const.pfmVoxelAligned) ~= 0 then
		for i = 1, #pos do
			local pt = self:GetVoxelSnapPos(pos[i])
			if pt then
				dest = dest or {}
				table.insert_unique(dest, pt)
			end
		end
	end
	dest = dest or pos

	local status = self:FindPath(dest, distance, min_distance)
	if self:GetPathPointCount() == 0 then
		if status == 0 then
			return true
		end
		return
	end

	-- cleanup stuff that prevents moving
	if self:HasStatusEffect("StationedMachineGun") then
		self:MGPack()
	elseif self:HasStatusEffect("ManningEmplacement") then
		self:LeaveEmplacement()
	elseif self:HasPreparedAttack() then
		self:InterruptPreparedAttack()
	end

	-- the target used for opportunity attacks
	self:SetTargetDummy(false)
	self:SetActionInterruptCallback(function(self)
		if not IsActivePaused() then
			self:SetCommand("GotoSlab")
		else
			self:SetQueuedAction()
			self:SetCommand("Idle")
		end
	end)
	self.goto_interrupted = interrupted
	self:PushDestructor(function(self)
		self:SetActionInterruptCallback()
		self.move_follow_target = nil
		self.move_follow_dest = nil
		self.goto_interrupted = nil
	end)
	self.move_follow_target = follow_target
	self.move_follow_dest = dest

	self:SetFootPlant(true)

	self.goto_target = pos

	local pfStep = self.Step
	local pfSleep = self.MoveSleep

	local target, target_time
	local is_moving = false

	Msg("UnitGoToStart", self)
	while true do
		self:TunnelsUnblock()
		if follow_pos and IsValid(follow_target) then
			if IsKindOf(follow_target.traverse_tunnel, "SlabTunnelLadder") then
				follow_target = false
				break
			end
			if follow_target:GetDist(follow_pos) > 0 then
				dest = self:GetClosestMeleeRangePos(follow_target)
				target = false
				follow_pos = follow_target:GetPos()
				self.move_follow_dest = dest
			end
		end
		if not target or self:GetPathPointCount() == 0 then
			status = self:FindPath(dest, distance, min_distance)
			if self:GetPathPointCount() == 0 then
				if status == 0 then
					status = pfFinished
				end
				break
			end
			local tunnel_start_idx = pf.GetPathNextTunnelIdx(self, const.TunnelMaskTraverseWait)
			if tunnel_start_idx then
				local tunnel_entrance = pf.GetPathPoint(self, tunnel_start_idx)
				local tunnel_exit = pf.GetPathPoint(self, tunnel_start_idx - 2)
				local last_target = target or self:GetPos()
				target = nil
				if last_target == tunnel_entrance or type(last_target) == "table" and table.find(last_target, tunnel_entrance) then
					if CanUseTunnel(tunnel_entrance, tunnel_exit, self) then
						self:TunnelBlock(tunnel_entrance, tunnel_exit)
						self:TunnelBlock(tunnel_exit, tunnel_entrance)
						local tunnel_start_idx2 = pf.GetPathNextTunnelIdx(self, const.TunnelMaskTraverseWait, tunnel_start_idx - 2)
						if tunnel_start_idx2 then
							local tunnel_entrance2 = pf.GetPathPoint(self, tunnel_start_idx2)
							local tunnel_exit2 = pf.GetPathPoint(self, tunnel_start_idx2 - 2)
							target = GetAlternateRoutesStartPoints(self, tunnel_entrance2, tunnel_exit2, const.TunnelMaskTraverseWait)
						else
							target = dest
						end
					end
				end
				if not target then
					target = GetAlternateRoutesStartPoints(self, tunnel_entrance, tunnel_exit, const.TunnelMaskTraverseWait)
				end
			elseif target ~= dest then
				target = dest
			end
			target_time = now()
			if target ~= dest then
				self:FindPath(target)
			end
			local pcount = self:GetPathPointCount()
			local next_pt = pcount > 1 and pf.GetPathPoint(self, pcount - 1) or nil
			if next_pt and not next_pt:IsValid() then
				next_pt = pcount > 2 and pf.GetPathPoint(self, pcount - 2) or nil
			end
			local angle = next_pt and CalcOrientation(self.target_dummy or self, next_pt)
			self:UpdateMoveAnim(nil, move_anim_type, next_pt)
			local move_anim = GetStateName(self:GetMoveAnim())
			if not GameTimeAdvanced then
				if next_pt then
					self:Face(next_pt)
				end
				if self:GetStateText() ~= move_anim then
					self:SetState(move_anim, 0, 0)
					self:RandomizeAnimPhase()
				end
			else
				self:PlayTransitionAnims(move_anim, angle)
				self:GotoTurnOnPlace(next_pt) -- face next target point
			end
		end
		local target_distance, target_min_distance
		if target == dest then
			target_distance = distance
			target_min_distance = min_distance
		else
			-- approaching tunnel. the tunnel can be destlocked, so the unit should destlock and wait
		end
		local wait
		status = pfStep(self, target, target_distance, target_min_distance)
		if status > 0 then
			if not is_moving then
				is_moving = true
				self:StartMoving()
			end
			while status > 0 do
				if not use_stop_anim or not self:GotoStopCheck() then
					pfSleep(self, status)
				end
				self:GotoAction()
				if follow_pos and IsValid(follow_target) and not follow_target:IsEqualPos(follow_pos) then
					if IsKindOf(follow_target.traverse_tunnel, "SlabTunnelLadder") then
						status = pfFinished
						dest = self:GetPos()
						target = dest
						break
					end
					local newdest = self:GetClosestMeleeRangePos(follow_target)
					if newdest ~= dest then
						dest = newdest
						target = newdest
					end
				end
				status = pfStep(self, target, target_distance, target_min_distance)
			end
		end
		if status == pfFinished and target == dest then
			break
		elseif status == pfFinished and target_time ~= now() then
			target = nil
		elseif status == pfTunnel then
			if IsActivePaused() then
				Sleep(1)
			end
			self:ClearEnumFlags(const.efResting) -- resting flag block the later ClearPath()
			local tunnel = pf.GetTunnel(self)
			if not tunnel then
				status = pfFailed
				break
			end
			if not self:InteractTunnel(tunnel) then
				status = pfFailed
				break
			end
			if not IsValid(tunnel) then
				tunnel = pf.GetTunnel(self)
			end
			local tunnel_in_use = IsValid(tunnel) and (tunnel.tunnel_type & const.TunnelMaskTraverseWait) ~= 0
				and not CanUseTunnel(tunnel:GetEntrance(), tunnel:GetExit(), self)
			if IsValid(tunnel) and not tunnel_in_use then
				if not is_moving then
					is_moving = true
					self:StartMoving()
				end
				local use_stop_anim = self.move_stop_anim_len > 0 and (pf.GetPathNextTunnelIdx(self, const.TunnelMaskWalkStopAnim) or 1) == self:GetPathPointCount()
				self:TraverseTunnel(tunnel, nil, nil, true, false, use_stop_anim)
				self:GotoAction()
			else
				target = nil -- the path is invalid, a new one should be cast
				wait = tunnel_in_use
			end
		elseif target ~= dest then
			wait = true
		else
			break
		end
		if wait then
			local anim = self:GetWaitAnim()
			if self:GetState() ~= anim then
				self:SetState(anim, const.eKeepComponentTargets)
			end
			local target_pos
			if IsPoint(target) then
				target_pos = target
			elseif IsValid(target) then
				target_pos = target:GetPos()
			else
				for i, p in ipairs(target) do
					if i == 1 or IsCloser(self, p, target_pos) then
						target_pos = p
					end
				end
			end
			if target_pos and not self:IsEqualPos2D(target_pos) then
				self:Face(target_pos)
			end
			if is_moving then
				is_moving = false
				self:StopMoving()
			end
			self:ClearPath()
			pfSleep(self, 200)
			self:GotoAction()
		end
	end

	self:PopAndCallDestructor()
	self.goto_target = false
	if is_moving then
		self:StopMoving()
	end
	Msg("UnitMovementDone", self)
	Msg("UnitGoTo", self)
	ObjModified(self)
	return status == pfFinished
end

function Unit:UninterruptableGoto(pos, straight_line)
	self:WaitResumeOnCommandStart()
	local wasInterruptable = self.interruptable
	if wasInterruptable then
		self:EndInterruptableMovement()
	end
	pos = self:GetVoxelSnapPos(pos) or pos
	assert(not self.goto_target) -- should be a top level Goto
	self.goto_target = pos
	self:UpdateMoveAnim()
	if straight_line then
		self:Goto(pos, "sl")
	else
		self:Goto(pos)
	end
	self.goto_target = false
	Msg("UnitMovementDone", self)
	if wasInterruptable then
		self:BeginInterruptableMovement()
	end
end

function Unit:Step(...)
	self:UpdateMoveSpeed()
	local status = AnimMomentHook.Step(self, ...)
	if status > 0 then
		if not self.combat_path and self.team and not self.team.neutral then
			local target_dummy = __unit_step_target_dummies[1]
			target_dummy.obj = self
			target_dummy.anim = self:GetWaitAnim()
			local interrupts = self:CheckProvokeOpportunityAttacks(CombatActions.Move, "move", __unit_step_target_dummies)
			self:ProvokeOpportunityAttacksWarning("move", interrupts)
			self:ProvokeOpportunityAttacks(CombatActions.Move, "move", target_dummy) -- traps
		end
		self:UpdateInWaterFX()
	end
	return status
end

function Unit:Goto(...)
	local pfStep = self.Step
	self:SetTargetDummy(false)
	self:UpdateMoveAnim()
	local status = pfStep(self, ...)
	if status >= 0 or status == pfTunnel then
		local topmost_goto, is_moving
		if not self.goto_target then
			topmost_goto = true
			self.goto_target = ...
		end
		local pfSleep = self.MoveSleep
		while true do
			if status > 0 then
				if not is_moving then
					is_moving = true
					self:StartMoving()
				end
				pfSleep(self, status)
			elseif status == pfTunnel then
				local tunnel = pf.GetTunnel(self)
				if not tunnel then
					status = pfFailed
					break
				end
				if not is_moving then
					is_moving = true
					self:StartMoving()
				end
				if not self:InteractTunnel(tunnel) then
					status = pfFailed
					break
				end
				if IsValid(tunnel) then
					self:TraverseTunnel(tunnel)
				end
			else
				break
			end
			status = pfStep(self, ...)
		end
		if is_moving then
			self:StopMoving()
		end
		if topmost_goto then
			self.goto_target = false
		end
		CombatPathReset(self)
		ObjModified(self)
	end

	local res = status == pfFinished
	Msg("UnitGoTo", self)
	return res
end

function Unit:IsInterruptable()
	if self.interruptable then
		if not self.goto_stance and not self.goto_hide then
			return true
		end
	end
	if self:IsIdleCommand() or self:HasQueuedAction() then
		return true
	end
	return false
end

function Unit:IsInterruptableMovement()
	return self.interruptable and (self.goto_target or self.move_attack_in_progress)
end

function Unit:InterruptCommand(...)
	self:Interrupt("SetCommand", ...)
end

function NetSyncEvents.InterruptCommand(unit, ...)
	unit:InterruptCommand(...)
end

function Unit:SetActionInterruptCallback(func)
	self.action_interrupt_callback = func
end

function Unit:Interrupt(func, ...)
	if self:IsInterruptable() then
		if not func and self.action_interrupt_callback then
			func = self.action_interrupt_callback
			self.action_interrupt_callback = false
		end
		if not func then
			return
		end
		if type(func) ~= "function" then
			func = self[func]
		end
		assert(func)
		if func then
			func(self, ...)
		end
		return
	end
	self.interrupt_callback = pack_params(func or false, ...)
end

function Unit:BeginInterruptableMovement()
	self.interruptable = true
	local callback = self.interrupt_callback
	if callback then
		self.interrupt_callback = false
		self:Interrupt(unpack_params(callback))
	end
end

function Unit:EndInterruptableMovement()
	self.interruptable = false
end

function Unit:IsEnemyPresent()
	if g_Combat then
		return true
	end
	local dlg = GetInGameInterfaceModeDlg()
	if dlg and dlg:HasMember("teams") then
		for i, t in ipairs(dlg.teams) do
			if not t.player_ally then
				return true
			end
		end
	end
	return false
end

function Unit:GetVoxelSnapPos(pos, angle, stance)
	if pos then
		if not pos:IsValid() then
			return
		end
	elseif not self:IsValidPos() then
		return
	end
	if not angle then
		angle = self:GetOrientationAngle()
	end
	local face_posx, face_posy, face_posz = RotateRadius(const.SlabSizeX, angle, pos or self, true)
	local pos = SnapToPassSlabSegment(pos or self, face_posx, face_posy, face_posz, const.TunnelMaskWalk)
	if not pos then
		return
	end
	if (stance or self.stance) == "Prone" then
		angle = FindProneAngle(self, pos, angle)
	end
	return pos, angle
end

function Unit:GetGridCoords()
	local x, y, z = self:GetPosXYZ()
	return PosToGridCoords(x, y, z)
end

function PosToGridCoords(x, y, z)
	z = z or terrain.GetHeight(x, y)
	local gx, gy, gz = WorldToVoxel(x, y, z)
	
	while true do
		local wx, wy, wz = VoxelToWorld(gx, gy, gz)
		if wz < z then
			gz = gz + 1
		else
			break
		end
	end	
	return gx, gy, gz
end

function Unit:EnterCombat()
	local wasInterruptable = self.interruptable
	if wasInterruptable then
		self:EndInterruptableMovement()
	end
	if not self:HasStatusEffect("ManningEmplacement") then
		self:UninterruptableGoto(self:GetVisualPos()) -- stop on the nearest free slab
		self:SetTargetDummyFromPos()
	end
	self:UpdateAttachedWeapons()

	if HasPerk(self, "SharpInstincts") then
		if self.stance == "Standing" then self:DoChangeStance("Crouch") end
		self:ApplyTempHitPoints(CharacterEffectDefs.SharpInstincts:ResolveValue("tempHP"))
	end

	if self:HasStatusEffect("ManningEmplacement") and self == SelectedObj then
		self:FlushCombatCache()
		self:RecalcUIActions(true)
		ObjModified("combat_bar")
	end
	Msg("UnitEnterCombat", self)
	if wasInterruptable then
		self:BeginInterruptableMovement()
	end
end

function Unit:AutoReload()
	local weapon = self:GetActiveWeapons("Firearm")
	local weapons = self:GetEquippedWeapons(self.current_weapon, "Firearm")
	local needs_reload
	local i = 1
	while not needs_reload and (i <= #weapons) do
		local w = weapons[i]
		if w and (w.ammo and w.ammo.Amount or 0) < w.MagazineSize then
			weapon = w
			needs_reload = true
			break
		end
		for slot, sub in sorted_pairs(weapons[i].subweapons) do
			if IsKindOf(sub, "Firearm") then
				weapons[#weapons + 1] = sub
			end
		end
		i = i + 1
	end
	
	--if weapon and (weapon.ammo and weapon.ammo.Amount or 0) < weapon.MagazineSize then
	if needs_reload then
		Sleep(self:Random(1000))
		local _, err = CombatActions.Reload:GetUIState({self})
		if err == AttackDisableReasons.NoAmmo then
			if not weapon.ammo or weapon.ammo.Amount == 0 then
				PlayVoiceResponse(self, "NoAmmo")
			else
				PlayVoiceResponse(self, "AmmoLow")
			end
		else
			RunCombatAction("ReloadMultiSelection", self, 0, {reload_all = true})
		end
	end
end

function Unit:ExitCombat()
	if self:IsNPC() and not self.dummy and (not self:IsDead() or self.immortal) then
		if self.retreating then
			local markers = MapGetMarkers("Entrance")
			local nearest, dist
			for _, marker in ipairs(markers) do
				local d = self:GetDist(marker)
				if not nearest or d < dist then
					nearest, dist = marker, d
				end
			end
			assert(nearest)
			self:SetCommand("ExitMap", nearest)
		end
	end
	
	self.ActionPoints = self:GetMaxActionPoints() -- reset AP so the units has all their actions available to initiate combat
	self.performed_action_this_turn = false
	
	if self:IsDowned() then
		self:SetCommand("DownedRally")
	elseif not self:IsDead() then
		self:PushDestructor(function()
			self:AutoReload()
		end)
		
		self:LeaveEmplacement(false, "exit combat")

		if self.combat_behavior == "Bandage" then
			self:EndCombatBandage(nil, "instant")
		elseif self.behavior == "Bandage" then
			self:SetBehavior()
		end
		
		if g_Pindown[self] then
			self:InterruptPreparedAttack()
		end

		if self:IsNPC() then
			if self.spawner then
				local x, y, z = self:GetGridCoords()
				local sx, sy, sz = PosToGridCoords(self.spawner:GetPosXYZ())
				if x == sx and y == sy and z == sz then
					local spawner_angle = self.spawner:GetAngle()
					self:SetAngle(spawner_angle)
				end
			end
		end
		
		if self:IsMerc() then 
			local allEnemies = GetAllEnemyUnits(self)
			local aliveEnemies = 0
			for _, enemy in ipairs(allEnemies) do 
				if not enemy:IsDead() and not enemy:IsDefeatedVillain() then
					aliveEnemies = aliveEnemies + 1
				end
			end
			if aliveEnemies == 0 then 
				self:DoChangeStance("Standing")
			end
		elseif self.species == "Human" and self.stance ~= "Standing" then
			self:DoChangeStance("Standing")
		end
		
		self:PopAndCallDestructor()
		
		if self:IsIdleCommand() then
			self:SetCommand("Idle") -- force restart to reevaluate the use of combat/civilian anims
		end
		self:UpdateAttachedWeapons()
	elseif self.immortal then
		self:ReviveOnHealth()
		self:ChangeStance(false, 0, "Standing")
		self:SetCommand("Idle")
	end
end

function Unit:GetStepActionFX()
	return self.is_moving and (self.move_step_fx or "StepRun") or "StepWalk"
end

function Unit:OnAnimMoment(moment, anim)
	anim = anim or GetStateName(self)
	local animFxName = FXAnimToAction(anim)
	PlayFX(animFxName, moment, self, self.anim_moment_fx_target)

	local anim_moments_hook = self.anim_moments_hook
	if type(anim_moments_hook) == "table" and anim_moments_hook[moment] then
		local method = moment_hooks[moment]
		return self[method](self, anim)
	end
end

-- behaviors
function Unit:GetCommandParam(name, command)
	command = command or self.command
	return self.command_specific_params and self.command_specific_params[command] and self.command_specific_params[command][name]
end

function Unit:GetCommandParamsTbl(command)
	command = command or self.command
	self.command_specific_params = self.command_specific_params or {}
	self.command_specific_params[command] = self.command_specific_params[command] or {}
	return self.command_specific_params[command]
end

function Unit:SetCommandParamValue(command, param, value)
	local param_tbl = self:GetCommandParamsTbl(command)
	param_tbl[param] = value
end

function Unit:SetCommandParams(command, params)
	command = command or self.command
	self.command_specific_params = self.command_specific_params or {}
	if params then
		self.command_specific_params[command] = params
		if params.weapon_anim_prefix then
			self:UpdateAttachedWeapons()
		end
	end
end

if FirstLoad then
	UnitIdleCommands = {
		[false] = true,
		["Idle"] = true,
		["IdleSuspicious"] = true,
		["AimIdle"] = true,
		["PreparedAttackIdle"] = true,
		["PreparedBombardIdle"] = true,
		["Dead"] = true,
		["VillainDefeat"] = true,
		["Hang"] = true,
		["Downed"] = true,
		["Cower"] = true,
		["CombatBandage"] = true,
		["ExitMap"] = true,
		["OverheardConversation"] = true,
		["OverheardConversationHeadTo"] = true,
	}

	UnitPreparedAttackBehaviors = {
		OverwatchAction = true,
		PinDown = true,
	}
	
	UnitIgnoreEnterCombatCommands = {
		["VillainDefeat"] = true,
	}
end

function Unit:IsUsingPreparedAttack()
	return UnitPreparedAttackBehaviors[self.combat_behavior]
end

function Unit:IsIdleCommand(check_pending)
	return UnitIdleCommands[self.command or false] and (not check_pending or (not self.pending_aware_state and not HasCombatActionInProgress(self)))
end

function Unit:HasQueuedAction()
	local action = CombatActions[self.queued_action_id]
	return action and (action.ActivePauseBehavior == "queue") and IsActivePaused()
end

function Unit:IsIdleOrRunningBehavior()
	if self:IsIdleCommand() then
		return true
	end
	if g_Combat then
		return self.command == self.combat_behavior
	end
	return self.command == self.behavior
end

function Unit:Idle()
	self:WaitResumeOnCommandStart()
	assert(self:IsValidPos())
	SetCombatActionState(self, nil)
	self.being_interacted_with = false
	if not self.move_attack_in_progress then
		self.move_attack_target = nil
	end	
	self:SetQueuedAction()
	ExplorationClearExclusiveAction(self)

	if self:IsDead() then
		if self.behavior == "Despawn" then
			self:SetCommand("Despawn")
		elseif self.behavior ~= "Hang" and self.behavior ~= "Dead" then
			self:SetBehavior("Dead")
			self:SetCombatBehavior("Dead")
		end
	else
		if self.stance == "Prone" and self:GetValidStance("Prone") ~= "Prone" then
			self:DoChangeStance("Crouch")
		end
		if g_Combat and self:CanCower() and (self.team.side == "neutral" or self:HasStatusEffect("ForceCower")) and not g_Combat:ShouldEndCombat() then
			self:SetCommand("Cower")
		end
	end
	self:UpdateInWaterFX()

	if self:IsDead() then
		if self.behavior == "Hang" then
			self:SetCommand("Hang")
		else
			assert(not self.Squad or IsMerc(self))
			self:SetCommand("Dead")
		end
	end
	FallDownCheck(self)
	if self:HasStatusEffect("Unconscious") then
		self:SetCommand("Downed")
	elseif IsSetpieceActor(self) then
		self:SetCommand("SetpieceIdle", true)
	elseif self:HasStatusEffect("Suspicious") then
		if g_Combat then
			self:RemoveStatusEffect("Suspicious")
		else
			return self:SuspiciousRoutine()
		end
	elseif self:HasCommandsInQueue() then
		return
	elseif g_Combat and self.combat_behavior then
		self:SetCommand(self.combat_behavior, table.unpack(self.combat_behavior_params or empty_table))
	elseif not g_Combat and self.behavior and not self:HasStatusEffect("Suspicious") then
		local enemy = self:GetCommandParam("idle_forcing_dist")
		if not IsValid(enemy) or not self:IdleForcingDist(enemy) then
			self:SetCommandParamValue(self.command, "idle_forcing_dist", nil)
			self:SetCommand(self.behavior, table.unpack(self.behavior_params or empty_table))
		end
	end

	-- setup target dummy
	local anim_style = self:GetIdleStyle()
	local base_idle = anim_style and anim_style:GetMainAnim() or self:GetIdleBaseAnim()
	local can_reposition = not (g_Combat and self:IsAware()) -- if large units can change angle (occupied tiles)
	local pos, orientation_angle
	if self.return_pos and not self.play_sequential_actions then
		pos = self.return_pos
		local voxel = SnapToVoxel(self)
		if not pos:Equal2D(voxel) then
			orientation_angle = CalcOrientation(pos, voxel)
		end
	else
		pos = GetPassSlab(self) or self:GetPos()
	end
	local dummy_orientation_angle = self:GetPosOrientation(pos, nil, self.stance, true, can_reposition)
	if not orientation_angle then
		orientation_angle = self.auto_face and dummy_orientation_angle or self:GetPosOrientation(pos, nil, self.stance, false, can_reposition)
	end
	self:SetTargetDummy(pos, dummy_orientation_angle, base_idle, 0)

	if g_Combat and (not self:IsNPC() or self:IsAware()) then
		Msg("Idle", self)
	end
	if self.aim_action_id and not HasCombatActionInProgress(self) then
		self:SetCommand("AimIdle")
	end
	self:SetWeaponLightFx(false)
	self:SetIK("AimIK", false)
	if self.play_sequential_actions then
		self:SetCommand("SequentialActionsIdle")
	end

	-- orient
	if not GameTimeAdvanced then
		self:SetOrientationAngle(orientation_angle)
	else
		self:EndInterruptableMovement()
		self:PlayTransitionAnims(base_idle, orientation_angle)
		self:AnimatedRotation(orientation_angle, base_idle)
		self:BeginInterruptableMovement()
	end

	self:SetCommandParamValue("Idle", "move_anim", "WalkSlow")
	if self:ShouldBeIdle() then
		-- one animation cycle
		-- play current style end animation
		self.cur_idle_style = anim_style and anim_style.Name or nil
		if anim_style then
			local anim = self:GetStateText()
			if anim_style:HasAnimation(anim) then
				if self:GetAnimPhase() ~= 0 and not self:IsAnimEnd() then
					Sleep(self:TimeToAnimEnd())
				end
			elseif anim == anim_style.Start then
				Sleep(self:TimeToAnimEnd())
			elseif (anim_style.Start or "") ~= "" and IsValidAnim(self, anim_style.Start) then
				self:SetState(anim_style.Start, const.eKeepComponentTargets)
				Sleep(self:TimeToAnimEnd())
			end
			self:SetState(anim_style:GetRandomAnim(self), const.eKeepComponentTargets)
			if not GameTimeAdvanced then
				self:RandomizeAnimPhase()
			end
		else
			if self:GetAnimPhase(1) == 0 or self:IsAnimEnd() or not IsAnimVariant(self:GetStateText(), base_idle) then
				self:SetRandomAnim(base_idle, const.eKeepComponentTargets, nil, true)
			end
		end
		Sleep(self:TimeToAnimEnd())
	else
		self:IdleRoutine()
	end
end

function Unit:IdleSuspicious()
	if self.stance == "Standing" and self.species == "Human" then
		local anim
		if self.gender == "Male" then
			anim = self:TryGetActionAnim("IdlePassive2", self.stance)
		else
			local weapon = self:GetWeaponAnimPrefix()
			if weapon == "nw" or self.carry_flare then
				anim = self:TryGetActionAnim("IdlePassive", self.stance)				
			elseif weapon == "mk" then
				anim = self:TryGetActionAnim("IdlePassive6", self.stance)
			else
				anim = self:TryGetActionAnim("IdlePassive2", self.stance)
			end
		end
		if self.carry_flare then
			anim = string.gsub(anim, "^%a*_", "nw_")
		end
		anim = self:ModifyWeaponAnim(anim)
		self:SetState(anim)
		Sleep(self:TimeToAnimEnd())
	end
	self:SetCommand("Idle")
end

function Unit:TakeSlabExploration()
	local pos, angle = self:GetVoxelSnapPos()
	if not pos then
		return
	end
	if GameTimeAdvanced then
		local vx, vy = SnapToVoxel(self:GetVisualPosXYZ())
		if not pos:Equal2D(vx, vy) then
			self:Goto(pos, "sl")
			pos, angle = self:GetVoxelSnapPos()
		end
	end
	self:SetPos(pos)
	self:SetOrientationAngle(angle)
end

function OnMsg.GatherFXMoments(list)
	table.insert_unique(list, "start")
	table.insert_unique(list, "end")
	table.insert(list, "action_start")
	table.insert(list, "action_end")
	table.insert(list, "WeaponGripStart")
	table.insert(list, "WeaponGripEnd")
	table.insert(list, "OrientationStart")
	table.insert(list, "OrientationEnd")
end

function Unit:OnMomentWeaponGripStart()
	self:SetWeaponGrip(true)
end

function Unit:OnMomentWeaponGripEnd()
	self:SetWeaponGrip(false)
end

function Unit:SequentialActionsStart()
	self.play_sequential_actions = true
end

function Unit:SequentialActionsEnd()
	if not self.play_sequential_actions then
		return
	end
	self.play_sequential_actions = false
	if self.command == "SequentialActionsIdle" then
		self:SetCommand("Idle")
	end
end

function Unit:SequentialActionsIdle()
	Halt()
end

function Unit:ReturnToCover(prefix, update_target_dummy)
	local pos = self.return_pos
	if not pos then
		return false
	end
	if not IsCloser(self, pos, const.SlabSizeX/2) and CanOccupy(self, pos) and IsPassSlabStep(self, pos) then
		local voxel_x, voxel_y = SnapToVoxel(self:GetPosXYZ())
		local angle = pos:Equal2D(voxel_x, voxel_y, 0) and self:GetAngle() or CalcOrientation(pos, voxel_x, voxel_y, 0)
		if update_target_dummy ~= false then
			self:SetTargetDummyFromPos(pos, angle)
		end
		local side = AngleDiff(self:GetVisualOrientationAngle(), angle) < 0 and "Left" or "Right"
		prefix = prefix or string.match(self:GetStateText(), "^(%a+_).*") or self:GetWeaponAnimPrefix()
		local anim = string.format("%s%s_Aim_End", prefix, side)
		self:SetIK("AimIK", false)
		self:SetFootPlant(true)
		if IsValidAnim(self, anim) then
			if self:CanQuickPlayInCombat() then
				self:SetPos(pos)
				self:SetOrientationAngle(angle)
			else
				anim = self:ModifyWeaponAnim(anim)
				self:SetPos(pos, self:GetAnimDuration(anim))
				self:RotateAnim(angle, anim)
			end
		else
			local msg = string.format('Missing animation "%s" for "%s"', anim, self.unitdatadef_id)
			StoreErrorSource(self, msg)
			self:SetPos(pos)
			self:SetOrientationAngle(angle)
		end
	end
	self.return_pos = false
	return true
end

function Unit:MovePlayAnimSpeedUpdate(anim, anim_flags, crossfade, dest)
	self:SetState(anim, anim_flags or 0, crossfade or -1)
	repeat
		self:SetAnimSpeed(1, self:CalcMoveSpeedModifier())
		local t = self:TimeToAnimEnd()
		if dest then
			self:SetPos(dest, t)
		end
	until not WaitWakeup(t)
end

function Unit:MovePlayAnim(anim, pos1, pos2, anim_flags, crossfade, ground_orient, angle, start_offset, end_offset, sleep_mod, acceleration)
	if not anim or not self:HasState(anim) then
		self:SetPos(pos2)
		self:SetFootPlant(true)
		return
	end
	if not angle then
		if pos1:Equal2D(pos2) then
			angle = self:GetAngle()
		else
			angle = CalcOrientation(pos1, pos2)
		end
	end
	if not pos1:IsValidZ() then
		pos1 = pos1:SetTerrainZ()
	end
	local pos2_3d = pos2:IsValidZ() and pos2 or pos2:SetTerrainZ()
	local t = self:GetVisualDist(pos1) == 0 and 100 or 0
	self:SetPos(pos1)
	self:SetFootPlant(false, t)
	self:SetOrientationAngle(angle, t)
	-- animation movement can be scaled only between "start" and "end" moments
	self:SetState(anim, anim_flags or const.eKeepComponentTargets, crossfade or -1)

	local anim_full_step = GetEntityStepVector(self:GetEntity(), anim)
	local use_animation_step = pos1 ~= pos2_3d and anim_full_step:Len() > 10*guic
	local duration = GetAnimDuration(self:GetEntity(), anim)
	local phase1 = self:GetAnimMoment(anim, "start") or 0
	local phase2 = self:GetAnimMoment(anim, "end")
	if not phase2 then
		local hit = self:GetAnimMoment(anim, "hit")
		phase2 = (hit or duration) - 200
	end
	if phase2 < phase1 then
		phase2 = phase1
	end
	start_offset = start_offset or point30
	end_offset = end_offset or point30

	if phase1 > 0 then
		-- [0 - action_start] - adjust the unit at proper action start position
		local action_phase1 = self:GetAnimMoment(anim, "action_start")
		if action_phase1 then
			action_phase1 = Min(action_phase1, phase1)
		else
			action_phase1 = phase1 / 2
		end
		if action_phase1 > 0 then
			local v = use_animation_step and self:GetStepVector(anim, angle, 0, action_phase1) or point30
			local dest = pos1 + v + start_offset
			local t = self:TimeToPhase(1, action_phase1) or 0
			self:SetPos(dest, t)
			Sleep(t)
		end
		-- [action_start - start scale] - play the animation as it is
		local v = use_animation_step and self:GetStepVector(anim, angle, 0, phase1) or point30
		local dest = pos1 + v + start_offset
		local t = self:TimeToPhase(1, phase1) or 0
		self:SetPos(dest, t)
		Sleep(t)
	end

	-- [scale] - the unit should reach the proper end position at the proper phase2 (the unit should be in the air)
	local v = use_animation_step and self:GetStepVector(anim, angle, phase2, duration - phase2) or point30
	local phase2_pos = pos2_3d - v + end_offset
	local t = phase2 > phase1 and self:TimeToPhase(1, phase2) or 0

	if t == 0 then
		self:SetPos(phase2_pos)
		if ground_orient then
			self:SetGroundOrientation(angle, t)
		end
	else
		local anim_speed, new_anim_speed
		if use_animation_step and self:IsCommandThread() then
			local extra_step_z = pos2_3d:z() - (pos1:z() + anim_full_step:z())
			local scale = 1000
			if anim_full_step:Len2D() > abs(anim_full_step:z()) then
				-- horizontal scale
				local extra_dist_2d = pos1:Dist2D(pos2) - anim_full_step:Len2D()
				if extra_dist_2d > const.SlabSizeX/4 then
					local anim_dist2d = abs(self:GetStepVector(anim, 0, phase1, phase2 - phase1):x())
					scale = anim_dist2d > 0 and MulDivRound(1000, anim_dist2d + extra_dist_2d, anim_dist2d) or 1000000
					scale = Min(scale, 1500) -- fix bugged animations with vely small steps
				end
				local fall_time = extra_step_z < 0 and self:GetGravityFallTime(abs(pos2_3d:z() - pos1:z()), -4000, const.Combat.Gravity) or 0
				if fall_time > phase2 - phase1 then
					scale = Max(scale, MulDivRound(1000, fall_time, phase2 - phase1))
				end
			else
				if extra_step_z < 0 and anim_full_step:z() <= -const.SlabSizeZ/2 then
				-- vertical scale
					scale = MulDivRound(1000, pos2_3d:z() - pos1:z(), anim_full_step:z())
				end
			end
			if scale ~= 1000 then
				anim_speed = self:GetAnimSpeed(1)
				new_anim_speed = MulDivRound(anim_speed, 1000, scale)
				self:SetAnimSpeed(1, new_anim_speed)
				t = self:TimeToPhase(1, phase2) or 0
			end
		end
		local acc = acceleration and self:GetAccelerationAndStartSpeed(phase2_pos, 0, t) or 0
		self:SetAcceleration(acc)
		self:SetPos(phase2_pos, t)
		if ground_orient then
			self:SetGroundOrientation(angle, t)
		end
		if acceleration or anim_speed then
			self:PushDestructor(function(self)
				if IsValid(self) then
					self:SetAcceleration(0)
					if anim_speed and self:GetAnimSpeed(1) == new_anim_speed then
						self:SetAnimSpeed(1, anim_speed)
					end
				end
			end)
		end
		Sleep(t)
		if acceleration or anim_speed then
			self:PopAndCallDestructor()
		end
	end

	-- [end scale - action end] - play the animation as it is
	local action_phase2 = self:GetAnimMoment(anim, "action_end")
	if action_phase2 then
		action_phase2 = Max(action_phase2, phase2)
	else
		action_phase2 =  phase2
	end
	if action_phase2 > phase2 then
		local v = self:GetStepVector(anim, angle, action_phase2, duration - action_phase2)
		local dest = pos2_3d - v + end_offset
		local t = self:TimeToPhase(1, action_phase2) or 0
		self:SetPos(dest, t)
		Sleep(t)
	end

	-- [action end - animation end] - reach pos2 to the animation end
	t = self:TimeToAnimEnd()
	if t >= 999999999 then
		assert(t < 999999999) -- can happen using editor
		t = 0
	end
	if sleep_mod then t = MulDivRound(t, sleep_mod, 100) end
	self:SetPos(pos2_3d, t)
	Sleep(t)
	self:SetPos(pos2)
	self:SetFootPlant(true)
end

function Unit:CanFaceEnemy(enemy)
	return not (enemy:IsDead() or enemy:IsDowned() or enemy:HasStatusEffect("Hidden"))
end

function Unit:IsConsideredEnemy(unit)
	if self:IsOnEnemySide(unit) then return true end
	for _, groupname in ipairs(self.Groups) do
		local group_modifiers = gv_AITargetModifiers[groupname]
		for group, _ in pairs(group_modifiers) do
			if table.find(unit.Groups, group) then
				return true
			end
		end
	end
end

function Unit:GetClosestEnemy(pos)
	if not IsValid(self) then return end
	pos = SnapToVoxel(pos or self)
	local face_targets = {}
	local threshold = const.SlabSizeX / 2
	local closest_enemy, min_dist
	-- check directly visible enemies
	local visibility = g_Visibility[self]
	for _, unit in ipairs(visibility) do
		if IsValid(unit) and (not min_dist or IsCloser(unit, pos, min_dist)) then
			local enemy = self:IsConsideredEnemy(unit)
			if IsValidTarget(unit) and enemy and self:CanFaceEnemy(unit) then
				table.insert(face_targets, unit)
				local dist = unit:GetDist(pos)
				if not closest_enemy or dist < min_dist then
					closest_enemy = unit
					min_dist = dist + threshold
				end
			end
		end
	end
	if not closest_enemy then
		return
	end
	if #face_targets > 1 then
		-- prefer targets closer to our current facing
		local cur_angle = self:GetAngle()
		local closest_adiff = abs(AngleDiff(CalcOrientation(pos, closest_enemy), cur_angle))
		for _, unit in ipairs(face_targets) do
			if unit ~= closest_enemy and IsCloser(unit, pos, min_dist) then
				local adiff = abs(AngleDiff(CalcOrientation(pos, unit), cur_angle))
				if adiff < closest_adiff then
					closest_enemy = unit
					closest_adiff = adiff
				end
			end
		end
	end
	return closest_enemy
end

function Unit:IsUsingCover()
	local cover = GetHighestCover(self)	
	return cover and (cover == 2 or cover == 1 and self.stance ~= "Standing")
end

function Unit:GetCoverToClosestEnemy(pos)
	pos = pos or self:GetVoxelSnapPos()
	if not pos or not pos:IsValid() then
		return
	end
	local enemies = table.copy(GetEnemies(self))
	local closest_enemy, closest_angle, closest_face_target, closest_dist
	local ow_target = self:GetOverwatchTarget()
	
	-- check for script-driven enemy relations
	for _, groupname in ipairs(self.Groups) do
		local group_modifiers = gv_AITargetModifiers[groupname]
		for target_group, mod in pairs(group_modifiers) do
			for _, obj in ipairs(Groups[target_group]) do
				if IsKindOf(obj, "Unit") then
					table.insert_unique(enemies, obj)
				end
			end
		end
	end	

	local function update_closest(check_pos, angle)
		for _, enemy in ipairs(enemies) do
			local dist = IsValid(enemy) and enemy:GetDist(check_pos)
			if dist and (not closest_dist or dist < closest_dist) then
				closest_enemy = enemy
				closest_dist = dist
				closest_angle = angle
				closest_face_target = check_pos
			end
		end
	end

	local covers
	if self:IsEnemyPresent() then
		covers = GetCoversAt(pos)
	end

	if not next(covers) then
		if ow_target then
			return false, ow_target
		end
		if #enemies == 0 then
			-- no covers, no enemies - nothing to face
			return
		else
			-- no covers - face the closest enemy
			update_closest(pos or self:GetPos())
			return false, closest_enemy
		end
	end

	local covers_count = table.count(covers)
	if covers_count == 1 then
		-- single cover only - face it no matter the enemies
		local angle, cover = next(covers)
		return cover, pos + GetCoverOffset(angle)
	end

	-- multiple covers
	if #enemies == 0 then
		local angle, cover = next(covers)	-- for now choose the 1st cover
		return cover, pos + GetCoverOffset(angle)
	end

	-- multiple covers, enemies around - choose the cover which center has the closest enemy
	for angle, cover in sorted_pairs(covers) do
		local cover_center = pos + GetCoverOffset(angle)
		update_closest(cover_center, angle)
	end
	local cover = covers[(closest_angle + 180*60) % (360*60)]

	return cover, closest_face_target
end

function Unit:GetPosOrientation(pos, angle, stance, auto_face, can_reposition)
	if not pos then
		pos = GetPassSlab(self) or self:GetPos()
	end
	if not pos:IsValid() then
		return 0
	end
	local bandage_target = self:GetBandageTarget()

	if not angle then
		 -- subsequent calls of self:GetOrientationAngle() can lead to small rotation
		angle = self:GetVisualOrientationAngle()
		if self.last_orientation_angle and abs(AngleDiff(angle, self.last_orientation_angle)) < 5*60 then
			angle = self.last_orientation_angle
		end
	end
	stance = stance or self.stance
	if self:HasStatusEffect("ManningEmplacement") then
		auto_face = false
	elseif IsValid(bandage_target) then
		auto_face = true
	end
	if auto_face == nil then
		auto_face = self.auto_face
	end

	-- face the nearest enemy and orient to high cover
	if g_Combat
		and auto_face
		and self:IsAware()
		and not self:HasStatusEffect("Exposed")
	then
		local to_face = IsValid(bandage_target) and bandage_target or self:GetClosestEnemy(pos)
		if to_face then
			angle = CalcOrientation(pos, to_face.return_pos or to_face)
		end
		if self.species == "Human" and (stance == "Standing" or stance == "Crouch") and GetHighestCover(pos) == const.CoverHigh then
			local face_angle
			if to_face then
				-- face the cover attack step out position
				local action = self:GetDefaultAttackAction("ranged")
				if action and action.AimType ~= "melee" then
					local lof_args = {
						action_id = action.id,
						obj = self,
						step_pos = pos,
						stance = "Standing",
						aimIK = false,
						prediction = true,
					}
					local lof_data = CheckLOF(to_face, lof_args)
					if lof_data and not IsCloser2D(pos, lof_data.step_pos, const.SlabSizeX/2) then
						face_angle = CalcOrientation(pos, lof_data.step_pos)
					end
				end
			end
			if not face_angle then
				face_angle = GetUnitOrientationToHighCover(pos, angle)
			end
			if face_angle then
				angle = face_angle
			end
		end
	end

	-- adjust angle of lying units to not collide with other units or environment
	if self.body_type == "Large animal" then
		local can_reposition = can_reposition ~= false or not self:IsEqualPos(pos)
		local snap_angle, fallback = FindLargeUnitAngle(self, pos, angle, can_reposition)
		angle = snap_angle or fallback or angle
	elseif self.species == "Human" and stance == "Prone" then
		angle = FindProneAngle(self, pos, angle)
	end
	return angle
end

function Unit:SetTargetDummyFromPos(pos, angle, can_reposition)
	pos = pos or GetPassSlab(self) or self:GetPos()
	if not pos:IsValid() or self:IsDead() then
		return self:SetTargetDummy(false)
	end
	local orientation_angle = self:GetPosOrientation(pos, angle, self.stance, true, can_reposition)
	local anim_style = GetAnimationStyle(self, self.cur_idle_style)
	local base_idle = anim_style and anim_style:GetMainAnim() or self:GetIdleBaseAnim()
	return self:SetTargetDummy(pos, orientation_angle, base_idle, 0)
end

function Unit:SetTargetDummy(pos, orientation_angle, anim, phase, stance, ground_orient)
	local dummy = self.target_dummy
	if dummy and dummy.locked then
		return
	end
	local changed
	if pos ~= false then
		pos = pos or GetPassSlab(self) or self:GetPos()
		--assert(CanOccupy(self, pos)) -- hit when loading savegames with units on impassable
		anim = anim or self:GetStateText()
		phase = phase or self:GetAnimPhase()
		stance = stance or self.stance
		if not orientation_angle then
			orientation_angle = self:GetOrientationAngle()
			if stance == "Prone" then
				orientation_angle = FindProneAngle(self, nil, orientation_angle, 60*60)
			end
		end
		if ground_orient == nil then
			ground_orient = select(2, self:GetFootPlantPosProps(stance))
		end
		if not dummy then
			if self.body_type == "Large animal" then
				dummy = PlaceObject("TargetDummyLargeAnimal", { obj = self })
			else
				dummy = PlaceObject("TargetDummy", { obj = self })
			end
			self.target_dummy = dummy
			changed = changed or "unit"
		end
		-- pos
		if changed or not dummy:IsEqualPos(pos) then
			dummy:SetPos(pos)
			changed = changed or "pos"
		end
		-- animation / phase
		if changed or dummy:GetStateText() ~= anim then
			dummy:SetState(anim)
			dummy:SetAnimSpeed(1, 0)
			changed = changed or "animation"
		end
		if changed or dummy:GetAnimPhase() ~= phase then
			dummy:SetAnimPhase(1, phase)
			changed = changed or "phase"
		end
		-- orientation
		local prev_angle, prev_axisx, prev_axisy, prev_axisz
		if not changed then
			prev_angle, prev_axisx, prev_axisy, prev_axisz = dummy:GetAngle(), dummy:GetVisualAxisXYZ()
		end
		if dummy.stance ~= stance then
			dummy.stance = stance
			changed = changed or "stance"
		end
		if ground_orient then
			dummy:ChangePathFlags(const.pfmGroundOrient)
			dummy:SetGroundOrientation(orientation_angle, 0)
		else
			dummy:ChangePathFlags(0, const.pfmGroundOrient)
			dummy:SetAxisAngle(axis_z, orientation_angle)
		end
		if not changed then
			local new_angle, new_axisx, new_axisy, new_axisz = dummy:GetAngle(), dummy:GetVisualAxisXYZ()
			if new_angle ~= prev_angle or new_axisx ~= prev_axisx or new_axisy ~= prev_axisy or new_axisz ~= prev_axisz then
				changed = true
			end
		end
		dummy:ClearEnumFlags(const.efResting)
		-- notify changed
	elseif dummy then
		changed = true
		DoneObject(dummy)
		self.target_dummy = false
	end
	if changed then
		Msg("TargetDummiesChanged", self)
		return true
	end
	return false
end

function Unit:GenerateTargetDummiesFromPath(path)
	path = path or self.combat_path
	local dummies = {}
	local base_idle = self:GetIdleBaseAnim(self.stance)

	local function AddDummyPos(pos, angle, insert_idx, last_step_pos)
		if pos ~= last_step_pos then
			table.insert(dummies, { obj = self, anim = base_idle, phase = 0, pos = pos, angle = angle, stance = self.stance, insert_idx = insert_idx })
		end
	end

	local p1 = self:GetPos()
	local angle = self:GetOrientationAngle()
	local dummy = self.target_dummy
	if dummy and dummy:GetPos() == p1 then
		table.insert(dummies, { obj = self, anim = dummy:GetStateText(), phase = dummy:GetAnimPhase(1), pos = dummy:GetPos(), angle = dummy:GetAngle(), insert_idx = #path + 1 })
	else
		AddDummyPos(p1, angle)
	end
	for i = #path, 1, -1 do
		local p0 = p1
		p1 = point(point_unpack(path[i]))
		if p0 ~= p1 then
			if not p0:Equal2D(p1) then
				angle = CalcOrientation(p0, p1)
			end
			local tunnel = pf.GetTunnel(p0, p1)
			if not tunnel then
				ForEachWalkStep(p0, p1, AddDummyPos, angle, i + 1, p1)
			end
			AddDummyPos(p1, angle)
		end
	end
	return dummies
end

function Unit:IsOnEnemySide(other)
	return self.team and other.team and band(self.team.enemy_mask, other.team.team_mask) ~= 0
end

function Unit:IsOnAllySide(other)
	return self.team and other.team and band(self.team.ally_mask, other.team.team_mask) ~= 0
end

function Unit:IsPlayerAlly()
	return self.team and self.team.player_ally
end

function Unit:ReportStatusEffectsInLog()
	--return not (self.team and self.team.side == "neutral")
	return const.DbgStatusEffects and not (self.team and self.team.side == "neutral")
end

local visibility_spots = {
	"Head", "Neck", --head
	"Shoulderl", "Shoulderr", --torso
	"Ribsupperl", "Ribsupperr",
	"Ribslowerl", "Ribslowerr",
	"Pelvisl", "Pelvisr",
	"Groin", --groin
	"Shoulderl", "Shoulderr", --arms
	"Elbowl", "Elbowr",
	"Wristl", "Wristr",
	"Kneel", "Kneer", --legs
	"Anklel", "Ankler",
}
local visibility_spot_indices = {}
function Unit:GetVisibilitySpotIndices()
	local entity = self:GetEntity()
	local current_state = self:GetState()
	
	local states = visibility_spot_indices[entity]
	local indices = states and states[current_state]
	
	if not indices then
		states = states or { }
		visibility_spot_indices[entity] = states
		
		indices = { }
		local n = 1
		for i=1,#visibility_spots do
			local spot_name = visibility_spots[i]
			local first, last = GetSpotRange(entity, 0, spot_name)
			for idx=first,last do
				indices[n] = idx
				n = n + 1
			end
		end
		states[current_state] = indices
	end
	
	return indices or empty_table
end

function Unit:IsNPC()
	local unit_data = UnitDataDefs[self.unitdatadef_id]
	return not unit_data or not unit_data.IsMercenary
end

function Unit:IsMerc()
	local unit_data = UnitDataDefs[self.unitdatadef_id]
	return unit_data and unit_data.IsMercenary
end

function Unit:IsCivilian()
	return self.team and self.team.side and self.team.side == "neutral" and self.species == "Human"
end

function GetMaxSightRadius()
	return const.Combat.AwareSightRange * const.Combat.SightModMaxValue / 100  * const.SlabSizeX + const.SlabSizeX / 4
end

function Unit:GetSightRadius(other, base_sight, step_pos)
	-- base sight radius, based on awareness (in-combat only) and illumination	
	local modifier = 100
	local other_is_unit = other and IsKindOf(other, "Unit") or false
	local hidden = other_is_unit and other:HasStatusEffect("Hidden")
	local sight = base_sight or (not hidden and self:IsAware() and const.Combat.AwareSightRange or const.Combat.UnawareSightRange)
	local night_time = GameState.Night or GameState.Underground
	if night_time and other and IsIlluminated(other, nil, nil, step_pos) then
		night_time = false
	end

	local force_min_sight = self:CallReactions_Or("OnCheckForceMinSight", self, other, step_pos, night_time)
	force_min_sight = force_min_sight or (IsKindOf(other, "Unit") and other:CallReactions_Or("OnCheckForceMinSight", self, other, step_pos, night_time))
	if force_min_sight then
		return MulDivRound(sight, const.Combat.SightModMinValue, 100) * const.SlabSizeX, hidden, night_time
	end
	modifier = self:CallReactions_Modify("OnCalcSightModifier", modifier, self, other, step_pos, night_time)
	if IsKindOf(other, "Unit") then
		modifier = other:CallReactions_Modify("OnCalcSightModifier", modifier, self, other, step_pos, night_time)
	end
	
	if other_is_unit and not other:IsDead() and not other:IsDowned() then
		if hidden then
			-- add (clamped) attrib difference as modifier
			local steath_mod = Max(0, MulDivRound(other.Agility - self.Wisdom, const.Combat.SightModStealthStatDiff, 100))		
			if other.stance == "Prone" then
				steath_mod = steath_mod + const.Combat.SightModHiddenProne
			end
			modifier = modifier - steath_mod
		end
		local armor = other:GetItemInSlot("Torso", "Armor")
		if armor and armor.Camouflage then
			modifier = modifier - const.Combat.CamoSightPenalty
		end
	end

	-- environmental factors
	if other then
		local env_factors = GetVoxelStealthParams(step_pos or other) or 0
		if band(env_factors, const.vsFlagTallGrass) ~= 0 then
			modifier = modifier + const.EnvEffects.BrushSightMod
		end
	end
	if night_time and other then
		local darknessMod = const.EnvEffects.DarknessSightMod
		if self:HasNightVision() then
			local penaltyReduce = CharacterEffectDefs.NightOps:ResolveValue("night_vision_penalty_reduction")
			darknessMod = MulDivRound(darknessMod, penaltyReduce, 100)
		end
		modifier = modifier + darknessMod
	end	
	if GameState.Fog then
		modifier = modifier + const.EnvEffects.FogSightMod
	end
	if GameState.DustStorm then
		modifier = modifier + const.EnvEffects.DustStormSightMod
	end
	if GameState.FireStorm then
		modifier = modifier + const.EnvEffects.FireStormSightMod
	end
	if other_is_unit then	-- height difference check
		local ox, oy, oz
		if step_pos then
			ox, oy, oz = PosToGridCoords(step_pos:xyz())
		else
			ox, oy, oz = other:GetGridCoords()
		end
		local x, y, z = self:GetGridCoords()
		if oz >= z + const.EnvEffects.SightHeightDiffThreshold then
			modifier = modifier + const.EnvEffects.SightHeightDiffMod
		elseif g_Exploration and oz + const.EnvEffects.SightHeightDiffThreshold < z  then
			modifier = modifier + -(const.EnvEffects.SightHeightDiffMod * 2)
		end
	end
	
	modifier = Clamp(modifier, const.Combat.SightModMinValue, const.Combat.SightModMaxValue)
	
	local sightAmount = MulDivRound(sight, modifier, 100) * const.SlabSizeX
	
	-- Prevent going in and out of sus state due to Pos/VisualPos differences.
	if self.command == "IdleSuspicious" then
		sightAmount = sightAmount + const.SlabSizeX / 4
	end
	
	return sightAmount, hidden, night_time
end

function Unit:CanSee(other, overridePos, overrideStance)
	local sight = self:GetSightRadius(other)
	local target = other
	if IsKindOf(other, "Unit") and other.visibility_override then
		target = stance_pos_pack(other.visibility_override.pos, StancesList[other.stance])
	elseif IsPoint(overridePos) then
		self = stance_pos_pack(overridePos, StancesList[overrideStance or self.stance])
	end
	if CheckLOS(target, self, sight) then
		return true
	end
	return false
end

function Unit:Face(...)
	if self.ground_orient then
		self:SetGroundOrientation(...)
	else
		CObject.Face(self, ...)
	end
end

function Unit:SetOrientationAngle(angle, ...)
	if self.ground_orient then
		self:SetGroundOrientation(angle, ...)
		self.last_orientation_angle = angle
	else
		CObject.SetAngle(self, angle, ...)
		self.last_orientation_angle = nil
	end
end

function Unit:GetOccupiedPos()
	return self.target_dummy and self.target_dummy:GetPos()
end

function Unit:GetVisualVoxels(pos, stance, voxels)
	local x, y, z 
	voxels = voxels or {}
	if pos then
		if type(pos) == "number" then
			x, y, z = point_unpack(pos)
		elseif IsPoint(pos) and pos:IsValid() then
			x, y, z = pos:xyz()
		else
			return voxels
		end
	else
		if not self:IsValidPos() then
			return voxels
		end
		x, y, z = self:GetPosXYZ()
	end
	if not z then
		z = terrain.GetHeight(x, y)
	end
	local snapped_z = select(3, VoxelToWorld(WorldToVoxel(x, y, z)))
	if z - snapped_z > const.SlabSizeZ / 2 then
		z = z + const.SlabSizeZ
	end
	x, y, z = WorldToVoxel(x, y, z)
	voxels[1] = point_pack(x, y, z)
	local head_voxel
	if self.species == "Human" then
		if (stance or self.stance) == "Prone" then
			head_voxel = voxels[1]
		else
			head_voxel = point_pack(x, y, z + 1)
			voxels[#voxels + 1] = head_voxel
		end
	elseif self.species == "Crocodile" then
		local angle = self:GetOrientationAngle()
		local sina, cosa = sincos(angle)
		local slabsize = const.SlabSizeX
		local dx = MulDivRound(slabsize, cosa, 4096)
		local dy = MulDivRound(slabsize, sina, 4096)
		if dx > slabsize/2 then dx = 1 elseif dx < -slabsize/2 then dx = -1 end
		if dy > slabsize/2 then dy = 1 elseif dy < -slabsize/2 then dy = -1 end
		voxels[#voxels + 1] = point_pack(x + dx, y + dy, z)
		voxels[#voxels + 1] = point_pack(x - dx, y - dy, z)
	end
	return voxels, head_voxel or voxels[1]
end

function Unit:ChangeStance(action_id, cost_ap, stance, args)
	self:WaitResumeOnCommandStart()
	if self.stance == stance or self.species ~= "Human" then
		self:GainAP(cost_ap)
		CombatActionInterruped(self)
		return
	end
	local pfclass = CalcPFClass(self.team and self.team.side, stance, self.body_type)
	local pos = GetPassSlab(self, pfclass)
	if not pos then
		self:GainAP(cost_ap)
		CombatActionInterruped(self)
		return
	end
	self:SetPos(pos)
	local wasInterruptable = self.interruptable
	if wasInterruptable then
		self:EndInterruptableMovement()
	end
	PlayFX("ChangeStance", "start", self)
	self:PushDestructor(function(self)
		PlayFX("ChangeStance", "end", self)
	end)
	local angle = args and args.angle
	if stance == "Prone" then
		angle = FindProneAngle(self, nil, angle)
	end
	if angle then
		self:SetOrientationAngle(angle, not GameTimeAdvanced and 0 or 100)
	end
	self:DoChangeStance(stance)
	self:PopAndCallDestructor() -- FX
	if wasInterruptable then
		self:BeginInterruptableMovement()
	end
end

local AnimationStance = {
	nw_Standing_MortarIdle = "Crouch",
	nw_Standing_MortarFire = "Crouch",
}

function Unit:GetHitStance()
	return AnimationStance[self:GetStateText()] or self.stance
end

function Unit:CanStealth(stance)
	if not self.team or self.team.side == "neutral"
		or not self:IsValidPos()
		or self:IsDead()
		or self:IsDowned()
		or self.command == "ExitCombat" and not self:HasStatusEffect("Hidden")
	then
		return false
	end
	stance = stance or self.stance
	local is_stealthy_stance
	if self.species == "Human" then
		is_stealthy_stance = stance ~= "Standing"
		if HasPerk(self, "FleetingShadow") then
			is_stealthy_stance = true
		end
	elseif self.species == "Crocodile" then
		is_stealthy_stance = true
	end
	if not is_stealthy_stance then
		return false
	end
	
	-- in combat allow Spotted units to remain Hidden for the duration of the effect
	local effects = self.StatusEffects
	local visual_contact = self.enemy_visual_contact
	if g_Combat and effects.Spotted then 
		visual_contact = false
	elseif not self:HasStatusEffect("Hidden") then
		local enemies = GetAllEnemyUnits(self)
		for _, enemy in ipairs(enemies) do
			visual_contact = visual_contact or HasVisibilityTo(enemy, self)
		end
	end
	if visual_contact then
		return false
	end
	if effects.BandagingDowned or effects.Revealed or effects.StationedMachineGun or effects.ManningEmplacement then
		return false
	end
	return true
end

function Unit:GetStanceToStealth(stance)
	stance = stance or self.stance
	if self.species == "Human" and stance == "Standing" and not HasPerk(self, "FleetingShadow") then
		return "Crouch"
	end
	return stance
end

function Unit:Hide()
	local stance = self:GetStanceToStealth()
	if not self:CanStealth(stance) then return end
	local wasInterruptable
	if stance ~= self.stance then
		wasInterruptable = self.interruptable
		if wasInterruptable then
			self:EndInterruptableMovement()
		end
		self:DoChangeStance(stance)
	end
	self:AddStatusEffect("Hidden")
	self:UpdateMoveAnim()
	PlayVoiceResponse(self, "BecomeHidden")
	if wasInterruptable then
		self:BeginInterruptableMovement()
	end
end

function Unit:Unhide()
	self.goto_hide = false
	self.goto_stance = false
	--self.marked_target_attack_args = false
	self:RemoveStatusEffect("Hidden")
	self:UpdateMoveAnim()
	if self:IsInterruptable() then
		self:BeginInterruptableMovement()
	end
end

function Unit:CanTakeCover()
	return self.species == "Human" and self.stance ~= "Prone" and (GetHighestCover(self.return_pos or self) or 0) > 0
end

function Unit:TakeCover()
	if not self:CanTakeCover() then
		return
	end
	self:InterruptPreparedAttack()
	self:AddStatusEffect("Protected")
	UpdateTakeCoverAction()
	self:DoChangeStance("Crouch")

	ObjModified(self)
end

function OnMsg.UnitAnyMovementStart(unit)
	unit:RemoveStatusEffect("Protected")
	UpdateTakeCoverAction()
end

function OnMsg.UnitStanceChanged(unit)
	if unit.stance ~= "Crouch" then
		unit:RemoveStatusEffect("Protected")
	end
end

local sneak_ui_update_thread = false

function OnMsg.UnitStealthChanged(obj)
	if obj == SelectedObj or table.find(Selection or empty_table, obj) then
		sneak_ui_update_thread = sneak_ui_update_thread or CreateGameTimeThread(function()
			while obj.command == "ExitCombat" do
				Sleep(100)
			end
		
			ObjModified("combat_bar")
			sneak_ui_update_thread = false
		end)
	end
end

function Unit:UpdateHidden()
	if self:HasStatusEffect("Hidden") then
		if not self:CanStealth() then
			self:RemoveStatusEffect("Hidden")
			self:UpdateFXClass()
		end
	elseif self.species ~= "Human" then
		if self:CanStealth() then
			self:AddStatusEffect("Hidden")
			PlayVoiceResponse(self, "BecomeHidden")
			self:UpdateFXClass()
		end
	end
end

-- used to control the fx actor class of the unit based on his Hidden status and self.visible
function Unit:UpdateFXClass()
	if not self.visible then
		self.fx_actor_class = "Hidden"
	elseif IsMerc(self) then
		self.fx_actor_class = "ImportantUnit"
	elseif self.species ~= "Human" then
		self.fx_actor_class = self.species
	elseif self:IsAmbientUnit() then
		if self.gender == "Male" then
			self.fx_actor_class = "AmbientMale"
		elseif self.gender == "Female" then
			self.fx_actor_class = "AmbientFemale"
		else
			self.fx_actor_class = "AmbientUnit"
		end
	else
		if self.gender == "Male" then
			self.fx_actor_class = "Male"
		elseif self.gender == "Female" then
			self.fx_actor_class = "Female"
		else
			self.fx_actor_class = "Unit"
		end
	end
end

function OnMsg.GetCustomFXInheritActorRules(rules)
	-- unit
	rules[#rules + 1] = "Male"
	rules[#rules + 1] = "Unit"
	rules[#rules + 1] = "Female"
	rules[#rules + 1] = "Unit"
	rules[#rules + 1] = "ImportantUnit"
	rules[#rules + 1] = "Unit"
	rules[#rules + 1] = "AmbientUnit"
	rules[#rules + 1] = "Unit"
	-- gender
	rules[#rules + 1] = "AmbientMale"
	rules[#rules + 1] = "Male"
	rules[#rules + 1] = "AmbientMale"
	rules[#rules + 1] = "AmbientUnit"
	rules[#rules + 1] = "AmbientFemale"
	rules[#rules + 1] = "Female"
	rules[#rules + 1] = "AmbientFemale"
	rules[#rules + 1] = "AmbientUnit"
end

local function UpdateHiddenUnits()
	for _, team in ipairs(g_Teams) do
		if team.side ~= "neutral" then
			for _, unit in ipairs(team.units) do
				unit:UpdateHidden()
			end
		end
	end
end

function OnMsg.UnitMovementDone(obj)
	if GameState.sync_loading then return end
	obj:RemoveStatusEffect("Focused")
	UpdateHiddenUnits()
	NetUpdateHash("UnitMovement", obj, obj:GetPosXYZ())
end

OnMsg.SyncLoadingDone = UpdateHiddenUnits
OnMsg.ExplorationStart = UpdateHiddenUnits

function Unit:GotoChangeStance(stance)
	if not stance or self.stance == stance then
		return
	end
	if not self:CanSwitchStance(stance) then
		return
	end
	local prev_stance = self.stance
	self.stance = stance
	ObjModified(self)
	self:UpdateMoveAnim()
	self:ChangePathFlags(const.pfDirty)
	self:UpdateHidden()
	ObjModified(self)
	if stance == "Prone" or prev_stance == "Prone" then
		local base_idle = self:GetIdleBaseAnim()
		PlayTransitionAnims(self, base_idle)
	end
	Msg("UnitStanceChanged", self)
end

function Unit:DoChangeStance(stance)
	assert(self.species == "Human" or stance == "")
	self.stance = HasPerk(self, "ZombiePerk") and "Standing" or stance
	self.aim_results = false
	self.aim_attack_args = false
	ObjModified(self)
	self:SetFootPlant(true)
	self:SetTargetDummyFromPos()
	self:UpdateMoveAnim()
	if GameTimeAdvanced then
		local base_idle = self:GetIdleBaseAnim()
		local angle = (self.target_dummy or self):GetOrientationAngle()
		PlayTransitionAnims(self, base_idle, angle)
		if not g_Combat and self.command ~= "ExitCombat" and self.command ~= "TakeCover" and self.command ~= "FallDown" then
			self:GotoSlab(self:GetPos())
		end
	end
	self:UpdateHidden()
	ObjModified(self)
	Msg("UnitStanceChanged", self)
end

if FirstLoad then
	g_StanceToStanceAP = {}
end
local function UpdateStanceToStanceAPCache()
	g_StanceToStanceAP = {}
	ForEachPresetInGroup("StanceToStanceAP", "Default", function(def)
		local t = g_StanceToStanceAP[def.start_stance]
		if not t then
			t = {}
			g_StanceToStanceAP[def.start_stance] = t
		end
		t[def.end_stance] = def.ap_cost
	end)
end
OnMsg.DataLoaded = UpdateStanceToStanceAPCache
OnMsg.PresetSave = UpdateStanceToStanceAPCache

function GetStanceToStanceAP(start_stance, end_stance)
	if start_stance == end_stance then
		return 0
	end
	return (g_StanceToStanceAP[start_stance] or empty_table)[end_stance]
end

function Unit:GetStanceToStanceAP(stance, ownStanceOverride)
	local currentStance = ownStanceOverride or self.stance
	if stance == currentStance then 
		return -1 
	end
	
	if HasPerk(self, "HitTheDeck") and stance == "Prone" then return 0 end
	
	return GetStanceToStanceAP(currentStance, stance) or 0	
end

function Unit:GetArchetype()	
	local arch = Archetypes[self.script_archetype]
	if arch then
		return arch
	end
	return Archetypes[self.current_archetype] or Archetypes.Soldier
end

function Unit:GetCurrentArchetype()
	return Archetypes[self.current_archetype] or Archetypes.Soldier
end

-- equipped items wihtout weapons, like Grenade, Medicine...
function Unit:GetEquippedQuickItems(class, slot_name)
	local items = {}
	self:ForEachItemInSlot(slot_name,class,function(item, s, l,t, items)
		if not item:IsWeapon() then
			items[#items+1] = item
		end	
	end, items)
	return items
end

function Unit:GetActiveWeapons(class, strict_order)
	if class == "UnarmedWeapon" then
		self.unarmed_weapon = self.unarmed_weapon or g_UnarmedWeapon
		return self.unarmed_weapon, nil, { self.unarmed_weapon }
	end

	if self:GetStatusEffect("ManningEmplacement") then
		local handle = self:GetEffectValue("hmg_emplacement")
		local obj = HandleToObject[handle]
		if obj and obj.weapon and (not class or IsKindOf(obj.weapon, class)) then
			obj.weapon.emplacement_weapon = true
			return obj.weapon, nil, { obj.weapon }
		end
	end
	
	local slot
	if IsSetpiecePlaying() and IsSetpieceActor(self) then
		slot = "SetpieceWeapon"
	else
		slot = self.current_weapon
	end

	self.combat_cache = self.combat_cache or {}
	local key = string.format("%s_%s%s", slot, class or "all", strict_order and "-strict" or "")
	local weapons = self.combat_cache[key]
	if not weapons then
		weapons = {}
		local firearms = {}
		self.combat_cache[key] = weapons
		local equipped = self:GetEquippedWeapons(slot)
		if slot == "SetpieceWeapon" and (#(equipped or empty_table) == 0) then
			equipped = self:GetEquippedWeapons(self.current_weapon)
		end

		for _, o in ipairs(equipped) do
			local match = not class or (class ~= "Firearm") or not IsKindOfClasses(o, "HeavyWeapon", "FlareGun")
			match = match and (not class or IsKindOf(o, class))
			if match then
				table.insert(weapons, o)
			end
			if IsKindOf(o, "FirearmBase") then
				table.insert(firearms, o)
			end
		end		
		-- second pass to add subweapons at the end of the list
		for _, item in ipairs(firearms) do
			for slot, weapon in sorted_pairs(item.subweapons) do
				local match = not class or (class ~= "Firearm") or not IsKindOfClasses(weapon, "HeavyWeapon", "FlareGun")
				match = match and (not class or IsKindOf(weapon, class))
				if match then
					table.insert(weapons, weapon)
				end
			end
		end
	end
	
	-- If weapon1 is exhausted and weapon 2 isnt then weapon2 is the main weapon
	if not strict_order then
		local weapon1Exhausted = not self:CanUseWeapon(weapons[1])
		local weapon2Exhausted = not self:CanUseWeapon(weapons[2])
		local weapon2IsntSubWeapon = weapons[1] and weapons[2] and not weapons[2].parent_weapon
		if weapons[1] and weapons[2] and weapon1Exhausted and not weapon2Exhausted and weapon2IsntSubWeapon then
			weapons[1], weapons[2] = weapons[2], weapons[1]
		end
	end
	
	return weapons[1], weapons[2], weapons
end

function UnitProperties:GetWeaponByDefIdOrDefault(class, def_id, packed_pos, item_id)
	if packed_pos then
		local weapon = self:GetItemAtPackedPos(packed_pos)
		return weapon
	else	
		local weapons = self:GetEquippedWeapons(self.current_weapon)
		local alt_slot = self.current_weapon == "Handheld A" and "Handheld B" or "Handheld A"
		table.iappend(weapons, self:GetEquippedWeapons(alt_slot))
		table.iappend(weapons, self:GetEquippedWeapons("Inventory"))
		local n = #weapons
		for i = 1, n do
			local weapon = weapons[i]
			if IsKindOf(weapon, "FirearmBase") then
				for _, sub in sorted_pairs(weapon.subweapons) do
					weapons[#weapons + 1] = sub
				end
			end
		end
		local matched
		if def_id then
			matched = table.ifilter(weapons, function(idx, item) return IsKindOf(item, def_id) end)
		end
		if #(matched or empty_table) == 0 then
			matched = weapons
		end
		if item_id then
			for _, weapon in ipairs(matched) do
				if weapon.id == item_id then
					return weapon
				end
			end
		end
		return matched[1]
	end
end

function Unit:OutOfAmmo(weapon, amount)
	weapon = weapon or self:GetActiveWeapons()
	return weapon and weapon:HasMember("ammo") and (not weapon.ammo or weapon.ammo.Amount < (amount or 1))
end

function Unit:GetSector()
	return gv_Sectors[gv_CurrentSectorId]
end

function Unit:IsWeaponJammed(weapon)
	weapon = weapon or self:GetActiveWeapons()
	return IsKindOf(weapon, "Firearm") and weapon.jammed
end

function Unit:CanUseWeapon(weapon, num_shots)
	if not weapon then
		return false, AttackDisableReasons.NoWeapon
	elseif weapon.Condition <= 0 then
		return false, AttackDisableReasons.WeaponBroken
	end
	if IsKindOf(weapon, "Firearm") then
		if weapon.jammed then
			return false, AttackDisableReasons.WeaponJammed
		elseif not weapon.ammo or weapon.ammo.Amount < (num_shots or 1) then
			return false, AttackDisableReasons.OutOfAmmo
		end
	end
	return true
end

AttackDisableReasons = {
	NoAP = T(526265371339, "<error>Insufficient AP</error>"),
	NoWeapon = T(379423324402, "<error>No active weapon</error>"),
	WeaponJammed = T(522229430242, "<error>The weapon is jammed</error>"),
	WeaponBroken = T(187856566334, "<error>The weapon is broken</error>"),
	OutOfAmmo = T(694516627561, "<error>Out of ammo</error>"),
	InsufficientAmmo = T(48284763278, "<error>Not enough ammo</error>"),
	InvalidTarget = T(332327094836, "<error>Invalid target</error>"),
	InvalidSelfTarget = T(858041242091, "<error>Cannot target self</error>"),
	NoTeamSight = T(308212362965, "<error>Out of team sight</error>"),
	NoTeamSightLivewire = T(316258123370, "<error>Out of sight (Livewire)</error>"),
	NoTarget = T(282471750002, "<error>No target</error>"),
	NoBandageTarget = T(409300745676, "<error>No target. Mercs with lowered max HP are healed in the Sat View.</error>"),
	OutOfRange = T(460146513440, "<error>Out Of Range</error>"),
	ExtremeRange = T(990882650338, "<error>Extreme range</error>"),
	CantReach = T(533577783995, "<error>Can't reach</error>"),
	NoLoS = T(871138850086, "<error>No line of sight</error>"),
	InsufficientMeds = T(589775173410, "<error>Not enough Meds</error>"),
	FullHP = T(270490338639, "<error>At full health</error>"),
	NoLockpick = T(179588362502, "<error>Can't pick a lock without a lockpick</error>"),
	NoCrowbar = T(871669664824, "<error>You need a crowbar to attempt to break this</error>"),
	NoCutters = T(457726671611, "<error>You need a wire cutter.</error>"),
	OnlyStanding = T(589960103330, "<error>Only available in Standing stance</error>"),
	Cooldown = T(591766545566, "<error>This action can be used once per turn</error>"),
	BandagingDowned = T(216477918933, "<error>Currently treating a downed ally</error>"),
	NoAmmo = T(958927508781, "<error>Out of ammo for this weapon</error>"),
	FullClip = T(342527613232, "<error>This weapon is already fully loaded</error>"),
	FullClipHaveOther = T(193803534966, "<error>This weapon is already fully loaded. You can change the ammo type from the inventory.</error>"),
	SignatureRecharge = T(422255119652, "<error>Can only be used once per conflict</error>"),
	SignatureRechargeOnKill = T(895217484195, "<error>Recharges on kill with another attack.</error>"),
	Water = T(389919921473, "<error>Not allowed in water</error>"),
	Stairs = T(377843918366, "<error>Not allowed on stairs</error>"),
	Impassable = T(150460717914, "<error>Impassable</error>"),
	Occupied = T(173250243531, "<error>Occupied</error>"),
	Indoors = T(927774491188, "<error>Cannot use indoors</error>"),
	InEnemySight = T(749326574456, "<error>You cannot sneak while in enemy sight.</error>"),
	Revealed = T(393250883796, "<error>You revealed yourself to the enemies and cannot sneak this turn.</error>"),
	CannotSneak = T(637272145762, "<error>You cannot sneak at this time.</error>"),
	WrongWeapon = T(734977105577, "<error>Wrong active weapon.</error>"),
	RangedWeapon = T(464635588615, "<error>Requires a Firearm.</error>"),
	MacheteWeapon = T(899395755721, "<error>Requires a Machete.</error>"),
	KnifeWeapon = T(270404087675, "<error>Requires a Knife.</error>"),
	CombatOnly = T(607543203128, "<error>Must be used during combat</error>"), 
	RequiresMachineGun = T(293921437394, "<error>Requires a Machine Gun</error>"), 
	RequiresUnarmed = T(252038182681, "<error>Must be Unarmed</error>"),
	NotInCover = T(553368221470, "<error>Only available in cover spots</error>"),
	AlreadyActive = T(492570194020, "Already active"),
	NotInMeleeRange = T(863084049025, "<error>Approach to attack</error>"),
	NotInBandageRange = T(576945352567, "<error>Approach to bandage</error>"),
	NotSneaking = T(465045630742, "<error>Must be sneaking</error>"),
	MinDist =  T(753745088840, "<error>Too close</error>"),
	NoLine =  T(127026985840, "<error>Straight path required</error>"),
	TooFar = T(137552442717, "<error>Too Far</error>"),
	UsingMachineGun = T(504207281345, "<error>Currently operating a machine gun</error>"),
	NoFireArc = T(698332993342, "<error>No fire arc</error>"),
}

function GetUnitNoApReason(unit)
	if unit:GetBandageTarget() then
		return AttackDisableReasons.BandagingDowned
	end
	return AttackDisableReasons.NoAP
end

function Unit:SetEffectValue(id, value)
	self.effect_values = self.effect_values or {}
	self.effect_values[id] = value or nil
end

function Unit:GetEffectValue(id)
	return self.effect_values and self.effect_values[id]
end

function Unit:GetEffectExpirationTurn(id, key)
	local store_key = string.format("%s:%s", id, key)
	return self.effect_values and self.effect_values[store_key] or -1
end

function Unit:SetEffectExpirationTurn(id, key, turn)
	local store_key = string.format("%s:%s", id, key)
	self.effect_values = self.effect_values or {}
	self.effect_values[store_key] = Max(turn, self.effect_values[store_key] or -1)
end

function Unit:CanAttack(target, weapon, action, aim, goto_pos, skip_ap_check, is_free_aim)
	if GetInGameInterfaceMode() == "IModeDeployment" then
		return false
	end
	if action.ActionType ~= "Melee Attack" and action.ActionType ~= "Ranged Attack" then 
		return false
	end
	local args
	if action then
		if action.ActionType == "Melee Attack" and target == self then
			return false, AttackDisableReasons.InvalidSelfTarget
		end
		if (action.ActionType == "Melee Attack" and action.AimType ~= "melee-charge") and IsValid(target) then
			if IsKindOf(target.traverse_tunnel, "SlabTunnelLadder") then
				return false, AttackDisableReasons.InvalidTarget
			end
			if not IsMeleeRangeTarget(self, goto_pos, nil, target) then
				local attack_pos = self:GetClosestMeleeRangePos(target)
				if not attack_pos or (IsKindOf(target, "Unit") and not IsMeleeRangeTarget(self, attack_pos, nil, target)) then
					return false, AttackDisableReasons.CantReach
				end
				local reason = g_Combat and AttackDisableReasons.CantReach or AttackDisableReasons.TooFar
				--[[if attack_pos then
					local cpath = GetCombatPath(self)
					local ap = cpath and cpath:GetAP(attack_pos)
					if ap and action:GetAPCost(self, args) <= self.ActionPoints - ap then
						reason = AttackDisableReasons.NotInMeleeRange
					end
				end
				return false, reason--]]
				if attack_pos then
					--local cpath = GetCombatPath(self)
					--local ap = cpath and cpath:GetAP(attack_pos)
					--if not ap or action:GetAPCost(self, args) > self.ActionPoints - ap then
					args = args or { target = target, goto_pos = attack_pos, aim = aim, ap_cost_breakdown = {} }
					local cost = action:GetAPCost(self, args)
					if cost < 0 or cost > self.ActionPoints then
						return false, reason
					end
				else
					return false, reason
				end
			end
		end
		if action.ActionType == "Ranged Attack" and target == self then -- no
			return false, AttackDisableReasons.InvalidTarget
		end
		if action.id == "UnarmedAttack" or action.id == "ExplodingPalm" or (action.id == "Brutalize" and not weapon) or action.id == "MarkTarget" then
			weapon = self:GetActiveWeapons("UnarmedWeapon")
		end
		if action.group == "SignatureAbilities" then
			local recharge = self:GetSignatureRecharge(action.id)
			if recharge then
				if recharge.on_kill then
					return false, AttackDisableReasons.SignatureRechargeOnKill
				end
				return false, AttackDisableReasons.SignatureRecharge
			end
		end
		if g_Combat and self:GetEffectExpirationTurn(action.id, "cooldown") >= g_Combat.current_turn then
			return false, AttackDisableReasons.Cooldown
		elseif not skip_ap_check and (g_Combat or g_StartingCombat or g_TestingSaveLoadSystem) then
			args = args or { target = target, goto_pos = goto_pos, aim = aim, ap_cost_breakdown = {} }
			local cost = action:GetAPCost(self, args)
			if not self:HasAP(cost, action.id, args) then
				return false, GetUnitNoApReason(self)
			end
		end
		if action.id == "OnMyTarget" then
			return true
		elseif action.id == "MGBurstFire" then
			if target and not CombatActionTargetFilters.MGBurstFire(target, {self}) then
				return false, AttackDisableReasons.OutOfRange
			end
		elseif action.id == "Bombard" or action.id == "FireFlare" then
			if self.indoors then
				return false, AttackDisableReasons.Indoors
			end
		elseif action.id == "PinDown" then
			if not CombatActionTargetFilters.Pindown(target, self, weapon) then
				return false, AttackDisableReasons.InvalidTarget
			end
		end
	end

	if not weapon then
		return false, AttackDisableReasons.NoWeapon
	elseif (weapon.Condition or 100) <= 0 then
		return false, AttackDisableReasons.WeaponBroken
	end

	if IsKindOf(weapon, "Grenade") or (IsKindOf(weapon, "HeavyWeapon") and weapon.trajectory_type == "parabola") then
		if action and target then
			local range = action:GetMaxAimRange(self, weapon)
			if goto_pos then
				if goto_pos:Dist(target) > range * const.SlabSizeX then
					return false, AttackDisableReasons.OutOfRange
				end 
			else
				if self:GetDist(target) > range * const.SlabSizeX then
					return false, AttackDisableReasons.OutOfRange
				end
			end

			args = args or { target = target, goto_pos = goto_pos, aim = aim, ap_cost_breakdown = {} }
			local results = action:GetActionResults(self, args)
			if not results.trajectory or #results.trajectory == 0 then
				return false, AttackDisableReasons.NoFireArc
			end
		end
		return true
	end

	local fireArm = IsKindOf(weapon, "Firearm")
	if fireArm and weapon.jammed then
		return false, AttackDisableReasons.WeaponJammed
	end

	local ammo_amount = fireArm and weapon:GetAutofireShots(action) or 1
	local min_ammo_amount = action:ResolveValue("min_shots")
	if fireArm and not ammo_amount then
		local params = weapon:GetAreaAttackParams(action.id, self)
		ammo_amount = params and params.used_ammo
	end
	ammo_amount = Min(ammo_amount or 1, min_ammo_amount or ammo_amount or 1)
	if action.ActionType ~= "Other" and self:OutOfAmmo(weapon, ammo_amount) then -- Non-attack actions dont require ammo
		return false, AttackDisableReasons.OutOfAmmo
	end

	if IsKindOf(weapon, "MeleeWeapon") and action.ActionType == "Ranged Attack" and target then
		local range = action:GetMaxAimRange(self, weapon)
		local attack_pos = goto_pos or self:GetPos()
		local target_pos = IsPoint(target) and target or target:GetPos()
		if attack_pos:Dist(target_pos) > range * const.SlabSizeX then
			return false, AttackDisableReasons.OutOfRange
		end
	end

	-- If you give me a target I will check it no matter whether you require one.
	local optionalTargetAndNoTarget = not action.RequireTargets and not target
	local invalidObjectTarget = not action.RequireTargets and not IsValid(target) and not IsPoint(target)
	local pointTarget = not action.RequireTargets and IsPoint(target)
	 
	if optionalTargetAndNoTarget or invalidObjectTarget or pointTarget then return true end
	local targetIsUnit = IsKindOf(target, "Unit")
	local targetIsTrap = IsKindOf(target, "Trap")
	local freeAimMeleeTarget = IsValid(target) and is_free_aim and action.ActionType == "Melee Attack"

	if not target and action.RequireTargets then
		return false, AttackDisableReasons.NoTarget
	end
	
	if not targetIsUnit and action.id == "Brutalize" then
		return false, AttackDisableReasons.InvalidTarget
	end

	if not targetIsUnit and not targetIsTrap and not freeAimMeleeTarget then
		return false, AttackDisableReasons.InvalidTarget
	end

	-- all attacks should be able to target all units except dead/defeated
	if targetIsUnit and (target:IsDead() or target:IsDefeatedVillain()) then
		return false, AttackDisableReasons.InvalidTarget
	end

	return true, false
end

function Unit:GetMoveModifier(stance, action_id)
	stance = stance or self.stance
	action_id = action_id or "Move"

	local modValue = 0
	
	if self:HasStatusEffect("Hidden") then
		modValue = modValue + Hidden:ResolveValue("ap_cost_modifier")
	end

	if GameState.DustStorm then
		modValue = modValue + const.EnvEffects.DustStormMoveCostMod
	end
	modValue = self:CallReactions_Modify("OnCalcMoveModifier", modValue, CombatActions[action_id])

	return modValue
end

function Unit:GetUIScaledAP()
	return self:GetUIActionPoints() / const.Scale.AP
end

function Unit:GetUIScaledAPMax()
	local max = Max(self:GetMaxActionPoints(), self:GetUIActionPoints())
	return max / const.Scale.AP
end

function Unit:GatherCTHModifications(id, value, data)
	if not id then return end
	
	data.meta_text = data.meta_text or {}
	data.mod_mul = 100
	data.mod_add = 0
	data.base_chance = value
	data.enabled = true

	Msg("GatherCTHModifications", self, id, data.action.id, data.target, data.weapon1, data.weapon2, data)
	self:CallReactions("OnModifyCTHModifier", id, self, data.target, data.action, data.weapon1, data.weapon2, data)
	if IsKindOf(data.target, "Unit") then
		data.target:CallReactions("OnModifyCTHModifier", id, self, data.target, data.action, data.weapon1, data.weapon2, data)
	end
	value = data.enabled and MulDivRound(value + data.mod_add, data.mod_mul, 100) or 0
	return value
end

function Unit:CalcChanceToHit(target, action, args, chance_only)
	-- Argument validation and fallbacks
	if not (IsPoint(target) or IsValid(target) and IsKindOf(target, "CombatObject")) then
		return 0
	end
	local weapon1, weapon2 = action:GetAttackWeapons(self)
	local weapon = args and args.weapon or weapon1
	if not weapon or IsKindOf(weapon, "Medicine") then
		return 0
	end

	local modifiers = not chance_only and {}
	
	if CheatEnabled("AlwaysHit") then
		if modifiers then 
			modifiers[#modifiers + 1] = {
				name = T(521586645369, "Cheat: Always Hit"),
				value = 100,
				id = "cheat"
			}
		end
		return 100, 100, modifiers
	elseif CheatEnabled("AlwaysMiss") then
		if modifiers then
			modifiers[#modifiers + 1] = {
				name = T(455715392693, "Cheat: Always Miss"),
				value = 0,
				id = "cheat"
			}
		end
		return 0, 0, modifiers
	end

	local target_spot_group = args and args.target_spot_group or nil
	if type(target_spot_group) == "table" then
		target_spot_group = target_spot_group.id
	end
	target_spot_group = target_spot_group or g_DefaultShotBodyPart
	if type(target_spot_group) == "string" then
		target_spot_group = Presets.TargetBodyPart.Default[target_spot_group]
	end

	local aim = args and args.aim or 0
	local opportunity_attack = args and args.opportunity_attack
	local attacker_pos = args and (args.step_pos or args.goto_pos) or self:GetPos()
	local target_pos = args and args.target_pos or IsPoint(target) and target or target:GetPos()

	local base = 0

	-- Base CTH
	local skill = self[weapon.base_skill]
	if action.id == "SteroidPunch" then
		skill = self["Strength"]
	end
	base = base + skill
	
	if args and not args.prediction then
		local effects = {}
		for i, effect in ipairs(self.StatusEffects) do
			effects[i] = effect.class
		end
		effects = table.concat(effects, ",")
		local target_effects = "-"
		if IsKindOf(target, "Unit") then
			target_effects = {}
			for i, effect in ipairs(target.StatusEffects) do
				target_effects[i] = effect.class
			end
			target_effects = table.concat(target_effects, ",")
		end
		NetUpdateHash("CalcChanceToHit_Base", self, target, action.id, weapon.class, weapon.id, base, effects, target_effects,
			weapon1 and weapon1.class, weapon1 and weapon1.id, weapon1 and weapon1.Condition, weapon1 and weapon1.MaxCondition,
			weapon2 and weapon2.class, weapon2 and weapon2.id, weapon2 and weapon2.Condition, weapon2 and weapon2.MaxCondition
		)
	end
	
	if modifiers then
		self.combat_cache = self.combat_cache or {}
		local key = "base_cth_" .. weapon.base_skill
		local skillmod = self.combat_cache[key]
		if not skillmod then
			local prop_meta = self:GetPropertyMetadata(weapon.base_skill)
			if prop_meta then
				skillmod =
				{
					name = prop_meta.name,
					value = skill
				}
			else
				assert(false, "weapon base skill '" .. weapon.base_skill .. "' property metadata not found!")
				skillmod =
				{
					name = T(462143455900, "Marksmanship"),
					value = skill
				}
			end
			self.combat_cache[key] = skillmod
		end
		table.insert(modifiers, skillmod)
	end

	local mod_data = {
		attacker = self,
		target = target,
		target_spot_group = target_spot_group,
		action = action, 
		weapon1 = weapon1, 
		weapon2 = weapon2, 
		aim = aim, 
		opportunity_attack = opportunity_attack, 
		attacker_pos = attacker_pos, 
		target_pos = target_pos,
		min = 0,
		max = 100,
	}


	-- Evaluate all modifiers
	ForEachPreset("ChanceToHitModifier", function(mod)
		if mod.RequireTarget and not IsValidTarget(target) then
			return
		end
		local req_action = mod.RequireActionType
		if req_action == "Any Attack" then
			if action.ActionType == "Other" then
				return
			end
		elseif req_action == "Any Melee Attack" then
			if action.ActionType ~= "Melee Attack" then
				return
			end
		elseif req_action == "Any Ranged Attack" then
			if action.ActionType ~= "Ranged Attack" then
				return
			end
		elseif req_action ~= action.id then
			return
		end
		
		local lof = false -- Currently unused by any modifier
		local apply, value, nameOverride, metaText, idOverride = mod:CalcValue(self, target, target_spot_group, action, weapon, weapon2, lof, aim, opportunity_attack, attacker_pos, target_pos)
		if args and not args.prediction then
			NetUpdateHash("CalcChanceToHit_Modifier", mod.id, apply, value)
		end
		if not apply then
			return
		end
		-- automated GatherCTHModifications provide a standard mechanism for replacing display name & adding meta text (only for the applicable mods)
		mod_data.display_name = nameOverride or mod.display_name
		mod_data.meta_text = (IsT(metaText) and {metaText} or metaText) or nil
		value = self:GatherCTHModifications(mod.id, value, mod_data)
		if args and not args.prediction then
			NetUpdateHash("CalcChanceToHit_Modifier_Mods", mod.id, value)
		end
		local nameOverride = mod_data.display_name
		local metaText = #mod_data.meta_text > 0 and mod_data.meta_text
		base = base + value
		if mod_data.enabled and modifiers then
			table.insert(modifiers, 
			{ 
				name = nameOverride or mod.display_name,
				value = value,
				id = idOverride or mod.id,
				metaText = metaText
			})
		end
	end)
	
	-- cycle status effects, running GatherCTHModifications() for every one of them, using the effect class/id as mod id
		-- this way status effects can implement their own cth modifiers via the same mechanism
	for _, effect in ipairs(self.StatusEffects) do
		mod_data.display_name = effect.DisplayName
		mod_data.meta_text = nil
		local value = self:GatherCTHModifications(effect.class, 0, mod_data)
		if args and not args.prediction then
			NetUpdateHash("CalcChanceToHit_Effect_Mods", effect.class, value)
		end
		if value and value ~= 0 then
			base = base + value
			if mod_data.enabled and modifiers then
				table.insert(modifiers, 
				{ 
					name = mod_data.display_name,
					value = value,
					id = effect.id,
					metaText = mod_data.meta_text
				})
			end
		end
	end
	
	-- process weaponcomponenteffects
	mod_data.weapon1 = nil
	mod_data.weapon2 = nil
	local weapons = {weapon1, weapon2}
	for _, weapon in ipairs(weapons) do
		if IsKindOf(weapon, "Firearm") then		
			for slot_id, component_id in sorted_pairs(weapon.components) do
				local def = WeaponComponents[component_id]
				local effects = def and def.ModificationEffects or empty_table
				if next(effects) ~= nil then
					mod_data.weapon1 = weapon
					mod_data.display_name = def.DisplayName
					mod_data.meta_text = nil
					local value = self:GatherCTHModifications(component_id, 0, mod_data)
					if args and not args.prediction then
						NetUpdateHash("CalcChanceToHit_Component_Mods", weapon.id, component_id, value)
					end
					if value and value ~= 0 then
						base = base + value
						if mod_data.enabled and modifiers then
							table.insert(modifiers, 
							{ 
								name = mod_data.display_name,
								value = value,
								id = component_id,
								metaText = mod_data.meta_text
							})
						end
					end
				end
			end
		end
	end
	
	mod_data.modifiers = modifiers
	self:CallReactions("OnCalcChanceToHit", self, action, target, weapon1, weapon2, mod_data)
	if IsKindOf(target, "Unit") then
		target:CallReactions("OnCalcChanceToHit", self, action, target, weapon1, weapon2, mod_data)
	end
	base = Max(0, mod_data.enabled and MulDivRound(base + mod_data.mod_add, mod_data.mod_mul, 100) or 0)

	local target_pos = IsPoint(target) and target or target:GetPos()
	local knife_throw = IsKindOf(weapon, "MeleeWeapon") and (action.ActionType == "Ranged Attack")
	local penalty = weapon:GetAccuracy(attacker_pos:Dist(target_pos), self, action, knife_throw) - 100
	local final = Clamp(base + penalty, 0, 100)
	final = Clamp(final, mod_data.min, mod_data.max)
		
	if args and not args.prediction then
		NetUpdateHash("CalcChanceToHit_Final", final)
	end
	
	if chance_only then
		return final
	end
	if penalty ~= 0 then
		if action.ActionType == "Melee Attack" then
			modifiers[#modifiers + 1] = {
				name = T(660754354729, "Weapon Accuracy"),
				value = penalty,
				id = "Accuracy"
			}
		elseif penalty <= -100 then
			modifiers[#modifiers + 1] = {
				name = T(162704513413, "Out of Range"),
				value = penalty,
				id = "Range"
			}
		else
			modifiers[#modifiers + 1] = {
				name = T(301586030557, "Range"),
				value = penalty,
				id = "Range"
			}
		end
	end
	return final, base, modifiers, penalty
end

-- unused
function Unit:GetBestChanceToHit(target, action, args, lof)
	local best_idx, best_hit_chance
	local list = attack_data.lof
	for i, hit_data in ipairs(list) do
		if i == 1 or hit_data.ally_hits_count <= list[best_idx].ally_hits_count then
			args.target_spot_group = hit_data.target_spot_group
			local hit_chance = self:CalcChanceToHit(target, action, args, "chance_only")
			if i == 1 or hit_data.ally_hits_count < list[best_idx].ally_hits_count or hit_chance > best_hit_chance then
				best_idx, best_hit_chance = i, hit_chance
			end
		end
	end
	return best_hit_chance, best_idx
end

function Unit:IsPointBlankRange(target)
	if not IsValid(target) then
		return false
	end
	return IsCloser(target, self, const.Weapons.PointBlankRange * const.SlabSizeX + 1)
end

function Unit:IsArmorPiercedBy(weapon, aim, target_spot_group, action) -- Can Crit
	local pierced = true
	if target_spot_group == "Head" then
		local helm = self:GetItemInSlot("Head")
		if helm and IsKindOf(helm, "IvanUshanka") then
			return false
		end
	end
	if action and action.id == "KalynaPerk" then
		return true, "ignored"
	end
	if action and action.ActionType == "Melee Attack" then
		return true, "ignored"
	end
	self:ForEachItem("Armor", function(item, slot)
		if slot ~= "Inventory" and item.Condition > 0 and weapon.PenetrationClass < item.PenetrationClass and (item.ProtectedBodyParts or empty_table)[target_spot_group] then
			pierced = false
			return "break"
		end
	end)
	return pierced
end

function Unit:CalcCritChance(weapon, target, action, args, attack_pos)
	if not IsKindOfClasses(weapon, "Firearm", "MeleeWeapon") then
		return 0
	end
	
	local target_spot_group = args and args.target_spot_group or g_DefaultShotBodyPart	
	local aim = args and args.aim or 0

	if IsKindOf(target, "Unit") and not target:IsArmorPiercedBy(weapon, aim, target_spot_group, action) then
		return 0
	end
	local critChance = self:GetBaseCrit(weapon) + (args and args.stealth_bonus_crit_chance or 0)
	local data = {
		crit_chance = critChance,
		action_id = action and action.id,
		weapon = weapon,
		aim = aim,
		opportunity_attack = args and args.opportunity_attack,
		opportunity_attack_type = args and args.opportunity_attack_type,
		crit_per_aim = const.Combat.AimCritBonus,
		stealth_attack = args and args.stealth_attack,
		target_spot_group = target_spot_group,
		guaranteed_crit = false,
		guaranteed_noncrit = false,
	}
	
	Msg("GatherCritChanceModifications", self, target, action and action.id, weapon, data)
	self:CallReactions("OnCalcCritChance", self, target, action, weapon, data)
	if IsKindOf(target, "Unit") then
		target:CallReactions("OnCalcCritChance", self, target, action, weapon, data)
	end
	
	if data.guaranteed_noncrit or data.opportunity_attack then return 0 end
	if data.guaranteed_crit then return 100 end

	local critChance = data.crit_chance + aim * data.crit_per_aim

	return Clamp(critChance, 0, 100)
end

function TFormat.AimAPCost()
	local igi = GetInGameInterfaceModeDlg()
	if not igi then return -1 end
	
	local attacker = igi.attacker
	local action = igi.action
	if not action then return -1 end
	
	local weapon = action:GetAttackWeapons(attacker)
	local crosshair = igi.crosshair
	local aimLevel = crosshair and crosshair.aim or 0
	
	local actionCost, aimCost = attacker:GetAttackAPCost(action, weapon, nil, aimLevel + 1, action.ActionPointDelta)
	return aimCost / const.Scale.AP
end

function Unit:GetAttackAPCost(action, weapon, action_ap_cost, aim, delta)
	if not weapon then 
		return 0
	end
	
	local min, max = self:GetBaseAimLevelRange(action, weapon)
	aim = Clamp(aim or 0, min, max) - min -- only charge for aiming above min level
	delta = delta or 0
	local aimCost = const.Scale.AP
	local rain_penalty = GameState.RainHeavy and not self.indoors
	if rain_penalty then
		aimCost = MulDivRound(aimCost, 100 + const.EnvEffects.RainAimingMultiplier, 100)
	end
	
	local ap = action_ap_cost or weapon.AttackAP or weapon.ShootAP or 0
	ap = ap + delta 
	ap = self:CallReactions_Modify("OnCalcAPCost", ap, action, weapon, aim)

	if IsKindOf(weapon, "HeavyWeapon") then
	elseif IsKindOf(weapon, "Firearm") or IsKindOf(weapon, "Grenade") or IsKindOf(weapon, "MeleeWeapon") then
		ap = ap + aim * aimCost
	else
		ap = -1
	end
	
	-- legal cheat: during heavy rain last possible aim costs 1 AP regardless of the penalty
	local remainingAP = (self:GetUIActionPoints() / 1000) * 1000
	if rain_penalty and ap > remainingAP and aim > 0 then 
		local diff = abs(remainingAP - ap)
		if diff < aimCost and diff >= const.Scale.AP then
			ap = remainingAP
			aimCost = 1000
		end
	end
	
	return ap, aimCost
end

function Unit:ResolveAttackParams(action_id, target, lof_params)
	local action = action_id and CombatActions[action_id]
	if action and action.AimType == "melee" then
		local attack_data = {
			obj = self,
			step_pos = self:GetOccupiedPos() or GetPassSlab(self) or self:GetPos(),
			target = target
		}
		return attack_data
	end
	lof_params = lof_params or {}
	lof_params.obj = self
	if not lof_params.action_id then
		lof_params.action_id = action_id
	end
	if lof_params.weapon == nil then
		lof_params.weapon = action and action:GetAttackWeapons(self) or false
	end
	if not lof_params.step_pos then
		lof_params.step_pos = self:GetOccupiedPos()
	end
	if lof_params.can_use_covers == nil then
		lof_params.can_use_covers = true
	end
	lof_params.prediction = true
	local attack_data = GetLoFData(self, target, lof_params)
	if not attack_data then
		attack_data = {
			obj = self,
			step_pos = self:GetOccupiedPos() or GetPassSlab(self) or self:GetPos(),
			target = target,
			stuck = true,
		}
	end
	return attack_data
end

function Unit:PrepareToAttack(attack_args, attack_results)
	if not self.visible then
		local targetIsUnit = attack_args.target and IsKindOf(attack_args.target, "Unit") and attack_args.target
		if targetIsUnit and targetIsUnit.visible then
			local floor = GetStepFloor(targetIsUnit)
			SnapCameraToObj(targetIsUnit, "force", floor)
		else
			return
		end
	end
	local showMiddle
	local dontMoveCamera, ccAttacker = StopCinematicCombatCamera()
	local updateLastUnitShoot = false
	if dontMoveCamera then updateLastUnitShoot = ccAttacker end
	local targetPos = not IsPoint(attack_args.target) and attack_args.target:GetVisualPos() or attack_args.target
	local notInGivenCommand = self.command ~= "OverwatchAction" and self.command ~= "MGSetup" and self.command ~= "MGTarget"
	local attackerPos = self:GetVisualPos()
	local isRetaliation = attack_args.opportunity_attack_type and attack_args.opportunity_attack_type == "Retaliation"
	local isAIControlled = not ActionCameraPlaying and not self:IsMerc() and g_AIExecutionController and 
		(not self.opportunity_attack or #g_CombatCamAttackStack == 0)
	local mercPlayingAsAI = self:IsMerc() and g_AIExecutionController and g_AIExecutionController.units_playing and g_AIExecutionController.units_playing[self]
	local isAIControlledMerc = not ActionCameraPlaying and (isRetaliation or attack_args.gruntyPerk or mercPlayingAsAI)
	local cameraPosChanged

	--Show attacker
	local movedToShowAttacker
	if isAIControlled or isAIControlledMerc then
		--handle camera
		if g_LastUnitToShoot ~= self and not dontMoveCamera then
			local midPoint = (attackerPos + targetPos) / 2
			local floor = GetStepFloor(self)
			local target_floor = GetStepFloor(attack_args.target)
			showMiddle = floor == target_floor and notInGivenCommand and DoPointsFitScreen({ attackerPos, targetPos }, midPoint, 10)
			local posToShow = showMiddle and midPoint or attackerPos
			local cameraIsNear = DoPointsFitScreen({posToShow}, nil, const.Camera.BufferSizeNoCameraMov)
			if cameraIsNear and showMiddle then
				cameraIsNear = DoPointsFitScreen({ attackerPos, targetPos }, nil, 10)
			end
			
			if not cameraIsNear then
				movedToShowAttacker = true
				SnapCameraToObj(posToShow, "force", GetStepFloor(showMiddle and targetPos or attackerPos))
				if not self:CanQuickPlayInCombat() then Sleep(1000) end
			elseif not IsVisibleFromCamera(self) or GetStepFloor(self) > cameraTac.GetFloor() then
				--no movement of camera should still take into account the floor
				cameraTac.SetFloor(GetStepFloor(self), hr.CameraTacInterpolatedMovementTime * 10, hr.CameraTacInterpolatedVerticalMovementTime * 10)
			end
			updateLastUnitShoot = self
		end
	elseif not ActionCameraPlaying and self.opportunity_attack and not isRetaliation then
		movedToShowAttacker = not DoPointsFitScreen({ targetPos }, nil, const.Camera.BufferSizeNoCameraMov)
		CombatCam_ShowAttackNew(self, attack_args.target, nil, attack_results, dontMoveCamera)
	end
	
	--handle badges
	if not g_AITurnContours[self.handle] and (isAIControlled or isAIControlledMerc or (self.opportunity_attack and not isRetaliation)) then
		local enemy = self.team.side == "enemy1" or self.team.side == "enemy2" or self.team.side == "neutralEnemy"
		g_AITurnContours[self.handle] = SpawnUnitContour(self, enemy and "CombatEnemy" or "CombatAlly")
		ShowBadgeOfAttacker(self, true)
	end

	self:AimTarget(attack_args, attack_results, true)

	--delay after aim
	if not self:CanQuickPlayInCombat() and movedToShowAttacker and (g_AIExecutionController or isRetaliation or attack_args.gruntyPerk or self.opportunity_attack) then
		local delay
		local consecutiveDelay = not dontMoveCamera and g_LastUnitToShoot == self

		if dontMoveCamera then
			delay = const.Combat.ShootDelayAfterAimCinematic
		elseif consecutiveDelay then
			delay = const.Combat.ConsecutiveShootDelayAfterAim
		else
			delay = const.Combat.ShootDelayAfterAim
		end
		Sleep(delay)
	end

	self:SetTargetDummy(nil, nil, attack_args.anim, 0, attack_args.stance)

	--Show target
	if not showMiddle then cameraPosChanged = not DoPointsFitScreen({targetPos}, nil, const.Camera.BufferSizeNoCameraMov) end
	if isAIControlled and notInGivenCommand and g_LastUnitToShoot ~= self or isAIControlledMerc then
		local interrupts = self:CheckProvokeOpportunityAttacks(attack_args.action_id and CombatActions[attack_args.action_id], "attack interrupt", {self.target_dummy or self})
		local targetNotVisible = showMiddle and IsKindOf(attack_args.target, "Unit") and not IsVisibleFromCamera(attack_args.target)
		CombatCam_ShowAttackNew(self, attack_args.target, interrupts, attack_results, dontMoveCamera or showMiddle, targetNotVisible)
	elseif self:IsMerc() and not ActionCameraPlaying and not g_AIExecutionController then
		--edge case where merc/player shoots but he is in overwatch so the overwatch will be shown first and then his attack
		local interrupts = self:CheckProvokeOpportunityAttacks(attack_args.action_id and CombatActions[attack_args.action_id], "attack interrupt", {self.target_dummy or self})
		if interrupts then
			CombatCam_ShowAttackNew(self, attack_args.target, interrupts, attack_results)
		else
			local cameraIsNear = DoPointsFitScreen({targetPos}, nil, const.Camera.BufferSizeNoCameraMov)
			if attack_results.explosion and (not attack_args.action_id or attack_args.action_id ~= "Bombard") and not cameraIsNear then
				SnapCameraToObj(targetPos, nil, GetStepFloor(targetPos), 500)
				Sleep(500)
			end
		end
	end

	--delay before shooting
	if not self:CanQuickPlayInCombat() then
		if g_AIExecutionController or isRetaliation or self.opportunity_attack then
			local delay
			local consecutiveDelay = not dontMoveCamera and g_LastUnitToShoot == self
			
			if dontMoveCamera then
				delay = const.Combat.ShootDelayCinematic
			elseif not cameraPosChanged then
				delay = const.Combat.ShootDelayTargetOnScreen
			elseif consecutiveDelay then
				delay = const.Combat.ConsecutiveShootDelay
			else
				delay = const.Combat.ShootDelay
			end
			Sleep(delay)
		elseif self.command ~= "PrepareBombard" and self.command ~= "OverwatchAction" then
			if cameraPosChanged then
				Sleep(const.Combat.ShootDelayNonAI)
			else
				Sleep(const.Combat.ShootDelayTargetOnScreen)
			end
		end
	end
	if updateLastUnitShoot then
		g_LastUnitToShoot = updateLastUnitShoot
	end
end

function Unit:CalcStealthKillChance(weapon, target, target_spot_group, aim)
	if not IsValidTarget(target) or not IsKindOf(target, "Unit") or not weapon then return 0 end

	local chance = Max(0, self.Dexterity - target.Wisdom)
	local min_chance = 1

	if target_spot_group == "Head" or target_spot_group == "Neck" then
		chance = chance + const.Combat.HeadshotStealthKillChanceMod
	end

	chance = self:CallReactions_Modify("OnCalcStealthKillChance", chance, self, target, weapon, target_spot_group, aim)
	chance = target:CallReactions_Modify("OnCalcStealthKillChance", chance, self, target, weapon, target_spot_group, aim)

	min_chance = self:CallReactions_Modify("OnCalcStealthKillMinChance", min_chance, self, target, weapon, target_spot_group, aim)
	min_chance = target:CallReactions_Modify("OnCalcStealthKillMinChance", min_chance, self, target, weapon, target_spot_group, aim)


	local stealthKillBonus = GetComponentEffectValue(weapon, "StealthKillBonusPerAim", "stealth_kill_bonus")
	if stealthKillBonus then
		chance = chance + (aim or 0) * (stealthKillBonus or 0)
	end
	
	if target:IsAware() then
		chance = MulDivRound(chance, 33, 100)
	elseif target:HasStatusEffect("Surprised") or target:HasStatusEffect("Suspicious") then
		chance = MulDivRound(chance, Max(0, 100 + CharacterEffectDefs.Surprised:ResolveValue("stealthkill_modifier")), 100)
	end
	
	if CheatEnabled("SkillCheck") then
		chance = 100
	end
	
	local weapon_pen_class = weapon:HasMember("PenetrationClass") and weapon.PenetrationClass or 1
	local armor_class = 0
	target:ForEachItem("Armor", function(item, slot)
		if slot ~= "Inventory" and item.ProtectedBodyParts and item.ProtectedBodyParts[target_spot_group] then
			armor_class = Max(armor_class, item.PenetrationClass)
		end
	end)
	if weapon_pen_class < armor_class and chance > 0 then
		chance = chance / 2
	end
	
	chance = Clamp(chance, min_chance, 100)
	return chance
end

function Unit:PrepareAttackArgs(action_id, args)
	action_id = action_id or self:GetDefaultAttackAction("ranged")
	args = args or empty_table
	local action = CombatActions[action_id]
	local weapon = args.weapon or action and action:GetAttackWeapons(self)
	local target = args.target
	local prediction = args.prediction or args.prediction == nil
	local aim_type = action and action.AimType
	local thermal_aim = IsKindOf(weapon, "Firearm") and IsFullyAimedAttack(args) and weapon:HasComponent("IgnoreGrazingHitsWhenFullyAimed")

	local attack_args = table.copy(args)
	attack_args.action_id = action_id
	attack_args.obj = self
	attack_args.weapon = weapon
	attack_args.target_pos = attack_args.target_pos or IsPoint(target) and target
	attack_args.step_pos = attack_args.step_pos or self.return_pos or self:GetOccupiedPos() or GetPassSlab(self) or self:GetPos()
	attack_args.ignore_smoke = thermal_aim
	if attack_args.fire_relative_point_attack == nil then
		attack_args.fire_relative_point_attack = self.WeaponType == "Shotgun"
	end
	attack_args.prediction = prediction

	if aim_type ~= "melee" then
		attack_args.prediction = true
		local attack_data
		if IsPoint(target) and attack_args.target_height_range then
			if not target:IsValidZ() then
				target = target:SetTerrainZ()
			end
			local min_dist
			for h = 0, attack_args.target_height_range, guim/2 do
				local pt = target:SetZ(target:z() + h)
				local data = GetLoFData(self, pt, attack_args)
				if data then
					local dist
					for _, lof_data in ipairs(data.lof) do
						for _, hit in ipairs(lof_data.hits) do
							local d = target:Dist(hit.pos)
							if not dist or dist > d then
								dist = d
							end
						end
					end
					if dist and (not attack_data or min_dist > dist) then
						attack_data, min_dist = data, dist
					end
				end
			end
		else
			attack_data = GetLoFData(self, target, attack_args)
		end
		if attack_data then
			for k, v in pairs(attack_data) do
				attack_args[k] = v
			end
		else
			attack_args.stuck = true
		end
		attack_args.prediction = prediction
	end

	attack_args.num_shots = attack_args.num_shots or 1 -- number of direct shots (with simulated projectiles
	attack_args.aoe_action_id = attack_args.aoe_action_id or false -- defines cone area for collateral/aoe damage (as used in Firearm:GetAreaAttackParams)
	attack_args.aoe_fx_action = attack_args.aoe_fx_action or false -- fx action to play for the aoe part of the attack, if any
	attack_args.aoe_damage_type = attack_args.aoe_damage_type or "default" -- "default", "fixed" or "percent", defines how the aoe damage is calculated
	attack_args.aoe_damage_value = attack_args.aoe_damage_value or false -- when "fixed" or "percent" type is used
	attack_args.applied_status = attack_args.applied_status or false -- status effect on hit
	attack_args.damage_bonus = attack_args.damage_bonus or false -- bonus damage applied by the attack (0/false = no change, 100 = x2, -100 = x0)
	attack_args.consumed_ammo = attack_args.consumed_ammo or false -- defaults to num_shots/used_ammo (from aoe params)
	attack_args.aoe_damage_bonus = attack_args.aoe_damage_bonus or false -- same as above for collateral/aoe damage
	attack_args.cth_loss_per_shot = attack_args.cth_loss_per_shot or false -- for attacks with num_shots > 1, defines the accuracy of the follow-up shots based on the attack roll
	attack_args.fx_action = attack_args.fx_action or false -- fx action to play in the hit moment(s) of the attack anim (defaults to WeaponFire)
	attack_args.single_fx = attack_args.single_fx or false -- if set to true, attacks will not play their fx_action more than once per attack

	if weapon and aim_type == "cone" then
		local aoe_params = weapon:GetAreaAttackParams(action_id, self, attack_args.target_pos, attack_args.step_pos)
		for k, v in pairs(aoe_params) do
			attack_args[k] = v
		end
	end

	-- Stealth kill
	local is_stealth = attack_args.stealth_attack or self:HasStatusEffect("Hidden")
	local lethal_weapon = (attack_args.target_spot_group == "Neck") and IsKindOf(weapon, "MeleeWeapon") and (weapon.NeckAttackType == "lethal")
	if action and (is_stealth or lethal_weapon)  then
		local stealth_targeted = is_stealth and action.StealthAttack and IsKindOf(target, "Unit") and IsValidTarget(target)
		local stealth_aoe, chance
		if stealth_targeted or stealth_aoe then
			local crosshair = GetInGameInterfaceModeDlg().crosshair
			local aim = args.aim or (crosshair and crosshair.aim) or 0
			chance = self:CalcStealthKillChance(weapon, target, attack_args.target_spot_group, aim)
			attack_args.stealth_attack = true
		end
		if lethal_weapon then
			local lethal_chance = 5 + Max(0, (self.Strength - target.Health) / 2)
			chance = Max(chance or 0, lethal_chance)
		end
		if stealth_targeted or lethal_weapon then
			if target:IsNPC() and not target.villain then
				attack_args.stealth_kill_chance = chance
				attack_args.stealth_bonus_crit_chance = 0
			else
				attack_args.stealth_kill_chance = 0
				attack_args.stealth_bonus_crit_chance = chance
			end
		end
	end

	return attack_args
end

function Unit:StartFireAnim(shot, attack_args, aim_pos, shotAnimDelay)
	if self:CanAimIK(attack_args.weapon) then
		if not aim_pos then
			aim_pos = shot and (shot.lof_pos2 or shot.target_pos) or attack_args.target_pos
		end
		if aim_pos then
			self:SetIK("AimIK", aim_pos) -- the unit should be in aim or fire state
			if shotAnimDelay then
				Sleep(shotAnimDelay)
				shotAnimDelay = 0
			else
				Sleep(200)
			end
		end
	end
	if (shotAnimDelay or 0) > 0 then
		Sleep(shotAnimDelay)
	end
	local hit_moment = shot and shot.hit_moment or "hit" -- todo: make sure DualShot passes the correct hit moments
	local anim = self:ModifyWeaponAnim(attack_args.anim)
	self:SetState(anim, const.eKeepComponentTargets, 0)
	local time_to_hit = self:TimeToMoment(1, hit_moment)
	if time_to_hit then
		Sleep(time_to_hit)
	end
end

function Unit:GetAttackRolls(num_shots, multishot, atk_value, crit_value)
	local attack_roll, crit_roll
	if not multishot or ((num_shots or 1) <= 1) then
		attack_roll = atk_value or (1 + self:Random(100))
		crit_roll = crit_value or (1 + self:Random(100))
	else
		attack_roll, crit_roll = {}, {}
		for i = 1, num_shots do
			attack_roll[i] = atk_value or (1 + self:Random(100))
			crit_roll[i] = crit_value or (1 + self:Random(100))
		end
	end
	return attack_roll, crit_roll
end

function FXAnimToAction(anim)
	return "Anim:" .. anim
end

function FXActionToAnim(action)
	return remove_prefix(action, "Anim:") or action
end

function Unit:GetLogName()
	return self:GetDisplayName()
end

function Unit:SetAttackReason(reason, opportunity_attack)
	self.attack_reason = reason
	self.opportunity_attack = opportunity_attack
end

function Unit:GetAttackReasonText()
	return self.attack_reason and T{295729060245, "<em><name></em>: ", name = self.attack_reason} or ""
end

function Unit:GetBaseDamage(weapon, target, breakdown)
	if self.infinite_dmg then
		return 10000
	end
	weapon = weapon or self:GetActiveWeapons()
	local mod = 100
	local base_damage = 0
			
	if IsKindOf(weapon, "Firearm") then
		base_damage = weapon.Damage
		if IsValidTarget(target) and self:GetDist(target) <= weapon.WeaponRange * const.SlabSizeX / 2  then
			local damageIncrease = GetComponentEffectValue(weapon, "HalfRangeDmgIncrease", "base_dmg_bonus")
			if damageIncrease then
				base_damage = base_damage + damageIncrease
			end
		end
	elseif IsKindOf(weapon, "Grenade") then
		if IsKindOf(weapon, "ThrowableTrapItem") then
			base_damage = weapon:GetBaseDamage()
		else
			base_damage = weapon.BaseDamage
		end
		mod = 100 + GetGrenadeDamageBonus(self)
	elseif IsKindOfClasses(weapon, "MeleeWeapon", "Ordnance") then
		base_damage = weapon.BaseDamage
	end
	
	local data = { base_damage = base_damage, modifier = mod, breakdown = breakdown or {} }
	Msg("CalcBaseDamage", self, weapon, target, data)
	self:CallReactions("OnCalcBaseDamage", weapon, target, data)
	return MulDivRound(data.base_damage, data.modifier, 100)
end

function Unit:GodMode(mode, state)
	mode = mode or "god_mode"
	if state == nil then 
		state = true 
	end
	self[mode] = state
	if mode == "god_mode" then
		self.infinite_ap = state
		self.infinite_ammo = state
		self.infinite_dmg = state
		self.infinite_condition = state
		self.invulnerable = state
	end
	if self.infinite_ap then
		self:GainAP(self:GetMaxActionPoints())
	end
end

local l_all_equiped_weapons_reloaded

function Unit:ReloadAllEquipedWeapons(ammo_type)
	l_all_equiped_weapons_reloaded = false
	self:ForEachItemInSlot("Handheld A", "Firearm", function(gun, slot, left, top, self, ammo_type)
		if ammo_type or not gun.ammo or gun.ammo.Amount < gun.MagazineSize then
			if self:ReloadWeapon(gun, ammo_type) then
				l_all_equiped_weapons_reloaded = true
			end
		end
	end, self, ammo_type)
	self:ForEachItemInSlot("Handheld B", "Firearm", function(gun, slot, left, top, self, ammo_type)
		if ammo_type or not gun.ammo or gun.ammo.Amount < gun.MagazineSize then
			if self:ReloadWeapon(gun, ammo_type) then
				l_all_equiped_weapons_reloaded = true
			end
		end
	end, self, ammo_type)
	return l_all_equiped_weapons_reloaded
end

function Unit:GetCoverPercentage(attackerPos, target_pos, stance)
	if g_Combat and self.combat_path then
		return false, false, 0 -- unit is moving in combat and does not benefit from cover
	end
	return GetCoverPercentage(target_pos or self:GetPos(), attackerPos, stance or self.stance)
end

function Unit:SetVisible(visible, force)
	visible = visible or (not force and IsSetpiecePlaying() and g_SetpieceFullVisibility)

	--NetUpdateHash("Unit:SetVisible", self, visible, force, IsSetpiecePlaying(), g_SetpieceFullVisibility)

	if visible then
		if g_Exploration  and not self:IsDead() then
			if not self.visible then
				self:SetOpacity(100, 500)
			end
		else
			self:SetOpacity(100)
		end

		local hidden_parts = self.Headshot and self.species == "Human" and HeadshotHideParts
		self:SetEnumFlags(const.efVisible)
		for name, body_part in pairs(self.parts) do
			if hidden_parts and table.find(hidden_parts, name) then
				body_part:ClearEnumFlags(const.efVisible)
			else
				body_part:SetEnumFlags(const.efVisible)
			end
		end
		if self.prepared_attack_obj then
			self.prepared_attack_obj:SetEnumFlags(const.efVisible)
		end
	else
		if g_Exploration and not self:IsDead() then
			if self.visible then
				self:SetOpacity(0, 2000)
			end
		else
			self:ClearEnumFlags(const.efVisible)
			for _, body_part in pairs(self.parts) do
				body_part:ClearEnumFlags(const.efVisible)
			end
		end

		if self.prepared_attack_obj then
			self.prepared_attack_obj:ClearEnumFlags(const.efVisible)
		end
	end
	
	if self.visible ~= visible then
		if self.melee_threat_contour then
			self.melee_threat_contour:SetVisible(visible)
		end
		
		if self.ui_badge then
			local badgeVisible = visible and not self:IsDead()
			self.ui_badge:SetVisible(badgeVisible, "unit")
		end
		
		self:SetSoundMute(not visible)
		self:ForEachAttach("GrenadeVisual", function(obj) 
			obj:SetSoundMute(not visible)
		end)
		self.visible = visible
		ObjModified(self)
		
		if self.carry_flare then
			self:UpdateOutfit()
		end
		
		self:UpdateFXClass()
	end
end

function Unit:GetVisibleEnemies()
	local visible = {}
	
	if self.team then
		-- Add all enemies visible by my team.
		local team_visible = g_Visibility[self.team] or empty_table
		for _, u in ipairs(team_visible) do
			if IsValidTarget(u) and self:IsOnEnemySide(u) then
				table.insert_unique(visible, u)
			end
		end
	end
		
	return visible
end

function Unit:OnGearChanged(isLoad)
	self.using_cumbersome = false
	NetUpdateHash("CumbersomeReset", self)
	self:ForEachItem(false, function(item, slot)
		if slot ~= "Inventory" and item:IsCumbersome() then
			self.using_cumbersome = true
			NetUpdateHash("CumbersomeSet", self)
		end
		item:ApplyModifiersList(item.applied_modifiers)
	end)
	Msg("UnitAPChanged", self)
	ObjModified(self)
	ObjModified(self.Inventory)
end

function Unit:CanUseIroncladPerk()
	local canUse = HasPerk(self, "Ironclad")

	if canUse then
		local weapons = self:GetHandheldItems()
		for _, weapon in ipairs(weapons) do
			if weapon:IsCumbersome() then
				canUse = false
				break
			end
		end
	end
	
	return canUse
end

local _is_attack_available_units = {}

function Unit:GetDefaultAttackAction(force_ranged, force_ungrouped, weapon, sync, ignore_stealth, args, ui)
	local weapon2
	if not weapon then
		weapon, weapon2 = self:GetActiveWeapons()
	end
	local id, action
	
	local weaponAttacks = IsKindOf(weapon, "Firearm") and not IsKindOfClasses(weapon, "HeavyWeapon", "FlareGun") and weapon.AvailableAttacks or empty_table
	local weapon2Attacks = IsKindOf(weapon2, "Firearm") and not IsKindOfClasses(weapon2, "HeavyWeapon", "FlareGun") and weapon2.AvailableAttacks or empty_table
	
	_is_attack_available_units[1] = self
	
	-- Check if dual shot.
	if #weaponAttacks > 0 and #weapon2Attacks > 0 then
		if table.find(weaponAttacks, "DualShot") and table.find(weapon2Attacks, "DualShot") then
			action = CombatActions.AttackDual
			if action:GetUIState(_is_attack_available_units, args) == "enabled" then
				id = action.id
			end
		end
	end

	if force_ranged and IsKindOf(weapon, "MeleeWeapon") and weapon.CanThrow then
		id = "KnifeThrow"
	end
	if IsKindOf(weapon, "FlareGun") then
		weapon = nil
		if weapon2 and not IsKindOf(weapon2, "FlareGun") then
			weapon = weapon2
			weapon2 = nil
		end
	end
	
	if not id then
		id = weapon and weapon:GetBaseAttack(self, force_ranged) or "UnarmedAttack"
	end	
	
	action = CombatActions[id]

	if force_ungrouped and action:GetUIState(_is_attack_available_units, args) == "enabled" then
		if sync then NetUpdateHash("GetDefaultAttackAction", self, id) end
		return action 
	end
	
	local firingMode = action and action.FiringModeMember
	if firingMode and CombatActions[firingMode]:GetUIState({self}, args) == "enabled" then
		if not force_ungrouped then
			if sync then NetUpdateHash("GetDefaultAttackAction", self, firingMode) end
			return CombatActions[firingMode]
		end
		local action_id = self:ResolveDefaultFiringModeAction(CombatActions[firingMode], ui, sync)
		if action_id then
			return CombatActions[action_id]
		end
	end
	if sync then	NetUpdateHash("GetDefaultAttackAction", self, action.id) end
	return action
end

local _resolve_default_firing_mode_actions = {}

function Unit:ResolveDefaultFiringModeAction(firingMode, ui, sync)
	local actions = _resolve_default_firing_mode_actions
	table.iclear(actions)
	local firing_id = firingMode.id

	local weapon = firingMode:GetAttackWeapons(self)
	if IsKindOf(weapon, "Firearm") then
		for _, id in ipairs(weapon.AvailableAttacks) do
			if CombatActions[id].FiringModeMember == firing_id then
				actions[#actions + 1] = CombatActions[id]
			end
		end
	else
		for id, action in pairs(CombatActions) do
			if action.FiringModeMember == firing_id then
				actions[#actions + 1] = action
			end
		end
	end

	-- special casea
	if firing_id == "AttackDual" then
		table.insert_unique(actions, CombatActions.LeftHandShot)
		table.insert_unique(actions, CombatActions.RightHandShot)
	elseif firing_id == "Attack" and weapon:HasComponent("EnableFullAuto") then
		table.insert_unique(actions, CombatActions.AutoFire)
	end
	table.sort(actions, function(a, b)
		return a.SortKey < b.SortKey
	end)

	if self:HasStatusEffect("Hidden") then
		if table.find(actions, "id", "SingleShot") then
			return "SingleShot", actions
		end
	end
	_is_attack_available_units[1] = self
	if ui and self.lastFiringMode and table.find(actions, "id", self.lastFiringMode) then
		local action = CombatActions[self.lastFiringMode]
		if action:GetUIState(_is_attack_available_units) == "enabled" then
			if self:HasAP(action:GetAPCost(self), action.id) then
				return action.id, actions
			end
		end
	end
	for _, action in ipairs(actions) do
		if action:GetUIState(_is_attack_available_units) == "enabled" then
			if not ui or self:HasAP(action:GetAPCost(self), action.id) then
				return action.id, actions
			end
		end
	end
	return actions[1] and actions[1].id, actions
end

local function ResetIdleLookAt(unit)
	if not g_Combat then
		return
	end
	for _, team in ipairs(g_Teams) do
		if team.side ~= "neutral" then
			for _, u in ipairs(team.units) do
				if u.command == "Idle" and u.target_dummy and u:IsAware() then
					local pos = GetPassSlab(u.target_dummy) or u.target_dummy:GetPos()
					if u:SetTargetDummyFromPos(pos, nil, false) then
						u:SetCommand("Idle")
					end
				end
			end
		end
	end
end

function UpdateIndoors(unit)
	if GameState.Underground then
		unit.indoors = true
		return
	end
	local volume = EnumVolumes(unit, "smallest")
	--unit.indoors = volume and not volume.dont_use_interior_lighting
	unit.indoors = volume and volume:HasRoof(true)
end

OnMsg.UnitMovementDone = ResetIdleLookAt
OnMsg.UnitDied = ResetIdleLookAt
OnMsg.VisibilityUpdate = ResetIdleLookAt
OnMsg.CoversChanged = ResetIdleLookAt
OnMsg.CombatObjectDied = ResetIdleLookAt

function OnMsg.EnterSector()
	for _, unit in ipairs(g_Units) do
		UpdateIndoors(unit)
		if HasPerk(unit, "ZombiePerk") then
			unit.stance = "Standing"
		end
	end
end

function OnMsg.UnitDied(dead_unit) -- bandage target death handler
	dead_unit:PlaceBlood()
	if not g_Combat then return end
	for _, unit in ipairs(g_Units) do
		if unit.combat_behavior == "CombatBandage" then
			local target = unit.combat_behavior_params[1]
			if target == dead_unit then
				unit:EndCombatBandage()
			end
		end
	end
end

local function UnitsUpdateCovers(bbox)
	MapForEach(bbox or "map", "Unit", function(u)
		if u:IsDead() or not u:IsAware() then
			return
		end
		if u:HasStatusEffect("Protected") and not GetCoversAt(u) then
			u:RemoveStatusEffect("Protected")
		end
		if u.command == "Idle" then
			u:SetCommand("Idle")
		end
	end)
end
OnMsg.CoversChanged = UnitsUpdateCovers
function OnMsg.CombatObjectDied(obj, bbox)
	UnitsUpdateCovers(bbox)
end

function Unit:SetHighlightColorModifier(visible)
	if not IsValid(self) then return "break" end
	if not visible then
		self.interactable_highlight_ctr = SpawnUnitContour(false, false, self.interactable_highlight_ctr)
	end

	local dead = self:IsDead()
	if not self:IsNPC() and not dead then return "break" end
	if dead then
		return Interactable.SetHighlightColorModifier(self, visible)
	end

	if visible == not not self.interactable_highlight_ctr then return "break" end
	self.interactable_highlight_ctr = SpawnUnitContour(self, "Interact", self.interactable_highlight_ctr)
	return "break"
end

if Platform.developer then
	function TestSpawnNPC(class, pos)
		local session_id = GenerateUniqueUnitDataId("TestNPC", gv_CurrentSectorId or "A1", class)
		return SpawnUnit(class, session_id, pos or GetCursorPos())
	end
end

TFormat.ap = function(context_obj, value)
	return T{747393774818, "<num> AP", num = value/const.Scale.AP}
end

TFormat.apn = function(context_obj, value)
	return T{867764319678, "<num>", num = type(value) == "number" and value/const.Scale.AP or value or ""}
end

function Unit:UpdatePFClass()
	if self.pfclass_overwritten then
		return
	end
	local side = self.team and self.team.side
	if (side == "player1" or side == "player2") and (self:HasStatusEffect("Panicked") or self:HasStatusEffect("Berserk")) then
		side = "enemy1" -- player units controlled by AI use the same pathfinding rules as the AI units
	end
	local pfclass = CalcPFClass(side, self.stance, self.body_type)
	self:SetPfClass(pfclass)
end

function Unit:OverwritePFClass(pfclass)
	if pfclass then
		self.pfclass_overwritten = pfclass
		self:SetPfClass(pfclass)
	elseif self.pfclass_overwritten then
		self.pfclass_overwritten = false
		self:UpdatePFClass()
	end
end

SuppressTeamUpdate = false

function Unit:SetTeam(team)
	local old_team = self.team
	local aware = self:IsAware()
	self.team = team
	self:UpdatePFClass()
	
	if old_team and team ~= old_team and old_team.side == "neutral" and not team.player_team then
		self:AddStatusEffect("Unaware")
	end
	
	if old_team and team ~= old_team and IsValidTarget(self) then
		local next_unit
		if table.find(Selection or empty_table, self) then
			SelectionRemove(self)
			if #Selection == 0 then
				next_unit = true
			end
		end
		if SelectedObj == self or next_unit then
			local igi = GetInGameInterfaceModeDlg()
			if igi then
				igi:NextUnit()
			end
		end
		if aware and team.side ~= "player1" and team.side ~= "player2" and team.side ~= "neutral" and team.side ~= old_team.side then
			if g_Combat then
				self:AddStatusEffect("Surprised")
			else
				self:AddStatusEffect("Suspicious")
			end
			if old_team and not GameState.sync_loading and not GameState.loading_savegame then
				for _, unit in ipairs(old_team.units) do
					PushUnitAlert("discovered", unit)
				end
				AlertPendingUnits()
			end
		end
	end

	Msg("UnitSideChanged", self, team)
	if not SuppressTeamUpdate then Msg("TeamsUpdated") end
end

function Unit:SetSide(side)
	if not g_Teams or #g_Teams == 0 then SetupDummyTeams() end

	local new_team = table.find_value(g_Teams, "side", side)
	SendUnitToTeam(self, new_team)
	self.CurrentSide = side
	if side ~= "neutral" then
		-- remove forced weapon anim prefix
		for command, params in pairs(self.command_specific_params) do
			params.weapon_anim_prefix = nil
		end
	end
	self:SyncWithSession("map")
end

function Unit:GetCombatMoveCost(pos)
	if point_pack(SnapToVoxel(pos:xyz())) == point_pack(SnapToVoxel(self:GetPosXYZ())) then
		return 0 -- the unit is in the same slab with the destination
	end
	local combatPath = GetCombatPath(self)
	local ap = combatPath:GetAP(pos)
	return ap
end

function Unit:GetClosestMeleeRangePos(target, target_pos, stance, interaction)
	local closest_pos
	if g_Combat then
		local combatPath = GetCombatPath(self, stance)
		closest_pos = combatPath:GetClosestMeleeRangePos(target, target_pos, true, interaction)
	else
		if target.behavior == "Visit" and IsKindOf(target.last_visit, "AL_SitChair") then
			return target.last_visit:GetPos()
		end
		local positions = GetMeleeRangePositions(self, target, target_pos, true)
		if positions then
			for i, packed_pos in ipairs(positions) do
				positions[i] = point(point_unpack(packed_pos))
			end
			local has_path, pf_closest_pos = pf.HasPosPath(self, positions)
			if has_path and table.find(positions, pf_closest_pos) then
				if interaction or not IsKindOf(target, "Unit") or IsMeleeRangeTarget(self, pf_closest_pos, stance, target, target_pos) then
					closest_pos = pf_closest_pos
				end
			end
		end
	end
	return closest_pos
end

function Unit:CalcAttackCostRange(action, target, item_id)
	if action.group == "FiringModeMetaAction" then
		local _, firingModeActions = GetUnitDefaultFiringModeActionFromMetaAction(self, action)
		local max, min = 0, 1000 * const.Scale.AP
		for i, fm in ipairs(firingModeActions) do
			local mode_min, mode_max = self:CalcAttackCostRange(fm, target)
			max = Max(max, mode_max)
			min = Min(min, mode_min)
		end
		return min, max
	end
	
	local min_aim, max_aim = self:GetBaseAimLevelRange(action)
	local args = {target = target, item_id = item_id}
	local min, max, display_cost
	
	for aim = min_aim, max_aim do
		args.aim = aim
		local ap = action:GetAPCost(self, args)
		if ap > 0 then
			min = Min(min, ap)
			max = Max(max, ap)
		end
	end
	return min, max
end

-- Returns the maximum aim level the unit can use to execute the provided action
function Unit:GetBaseAimLevelRange(action, target)
	if not action.IsAimableAttack then return 0, 0 end
	local actionWep = action:GetAttackWeapons(self)
	local min, max = 0, 0
	if IsKindOfClasses(actionWep, "Firearm", "MeleeWeapon") then
		max = actionWep.MaxAimActions
	end
	if max > 0 then
		max = self:CallReactions_Modify("OnCalcMaxAimActions", max, self, target, action, actionWep)
		if IsKindOf(target, "Unit") then
			max = target:CallReactions_Modify("OnCalcMaxAimActions", max, self, target, action, actionWep)
		end
		min = self:CallReactions_Modify("OnCalcMinAimActions", min, self, target, action, actionWep)
		if IsKindOf(target, "Unit") then
			min = target:CallReactions_Modify("OnCalcMinAimActions", min, self, target, action, actionWep)
		end
		max = Max(max, min)
	end
	
	return min, max
end

function Unit:GetAimLevelRange(action, target, goto_pos, is_free_aim)
	local minAim, maxCurrent, maxTotal
	minAim, maxTotal = self:GetBaseAimLevelRange(action, target)
		
	for i = 1, maxTotal do
		if action:GetUIState({self}, { target = target, aim = i, goto_pos = goto_pos, free_aim = is_free_aim }) ~= "enabled" then
			maxCurrent = i - 1
			break
		end
	end
	
	return minAim, (maxCurrent or maxTotal), maxTotal
end

function Unit:JoinSquadAs(merc_id, squad)
	local unit = SpawnUnit(merc_id, merc_id, self:GetPos(), self:GetAngle())
	unit:ApplyAppearance(self.Appearance)
	unit:SetState(self:GetState(), 0, 0)
	unit:SetAnimPhase(1, self:GetAnimPhase())
	unit.stance  = self.stance
	unit.current_weapon = self.current_weapon

	local weapon1, weapon2 = self:GetActiveWeapons(false, "strict")
	if IsKindOf(weapon1, "Firearm") then
		unit:Attach(weapon1:CreateVisualObj(unit), unit:GetSpotBeginIndex("Weaponr"))
	end
	if IsKindOf(weapon2, "Firearm") then
		unit:Attach(weapon2:CreateVisualObj(unit), unit:GetSpotBeginIndex("Weaponl"))
	end

	self.villain = false
	self.HitPoints = 0
	self:ClearHierarchyEnumFlags(const.efVisible)

	local tidx = g_Teams and table.find(g_Teams, "side", squad.Side)
	if tidx then
		table.insert(g_Teams[tidx].units, unit)
		unit:SetTeam(g_Teams[tidx])
		ObjModified(unit.team)
	end
	
	AddToGlobalUnits(unit)

	-- Check if trying to join a full squad.
	local unitCount, unitCountWithJoining = GetSquadUnitCountWithJoining(squad.UniqueId)
	if unitCountWithJoining >= const.Satellite.MercSquadMaxPeople then
		local oldSector, oldVisualPos = squad.CurrentSector, squad.VisualPos
		local name = SquadName:GetNewSquadName("player1")
		local squadParams = {Side = "player1", CurrentSector = oldSector, VisualPos = oldVisualPos, Name = name}
		local squad_id = CreateNewSatelliteSquad(squadParams, {merc_id})
		squad = gv_Squads[squad_id]
		Msg("UnitJoinedPlayerSquad",squad_id)
	else
		AddUnitsToSquad(squad, {merc_id}, nil, InteractionRand(nil, "Satellite"))
	end
	
	-- Mark unit as spawned, so satellite doesnt respawn.
	local newUd = gv_UnitData[unit.session_id]
	assert(newUd)
	newUd.already_spawned_on_map = true
	unit.already_spawned_on_map = true

	-- Remove old UD from its squad.
	local ud = gv_UnitData[self.session_id]
	if ud then
		RemoveUnitFromSquad(ud, "despawn")
	end

	if g_Combat then
		Msg("UnitEnterCombat", unit)
	end
	Msg("TeamsUpdated")

	DoneObject(self)
	Msg("UnitJoinedAsMerc", unit)
end

function OnMsg.UnitJoinedPlayerSquad()
	if g_Combat then
		ObjModified(g_Combat)
	else
		ForceUpdateCommonUnitControlUI()
	end
end

function GetBehaviorGroups()
	local marker_groups = {}
	for id, group in sorted_pairs(Groups) do
		for _, o in ipairs(group) do
			if IsKindOf(o, "WaypointMarker") or (IsKindOf(o, "GridMarker") and (o.Type == "Position" or o.Type=="Entrance") )then
				marker_groups[#marker_groups + 1] = id
				break
			end
		end
	end
	return marker_groups
end

MapVar("gv_UnitGroups",false)
MapVar("gv_NPCGroups",false)
MapVar("gv_TargetUnitGroups",false)

local groups_separator = "-----------------"

function GetUnitSpawnMarkerGroups()
	local marker_groups = {}
	
	MapForEach("map", "UnitMarker", function(marker, marker_groups)
		table.iappend(marker_groups, marker.Groups or empty_table)
	end, marker_groups)
	
	MapForEachMarker("Defender", false, function(marker, marker_groups)
		table.iappend(marker_groups, marker.Groups or empty_table)
	end, marker_groups)
	
	MapForEachMarker("DefenderPriority", false, function(marker, marker_groups)
		table.iappend(marker_groups, marker.Groups or empty_table)
	end, marker_groups)
	
	table.sort(marker_groups)
	-- remove duplicates
	for i = #marker_groups, 2, -1 do
		if marker_groups[i] == marker_groups[i - 1] then
			table.remove(marker_groups, i)
		end
	end
	return marker_groups
end

function GetUnitGroups()
	if not gv_UnitGroups then
		RecalcGroups()
	end
	return gv_UnitGroups
end

function GetTargetUnitCombo()
	if not gv_TargetUnitGroups and not IsChangingMap() then
		RecalcGroups()
	end
	return gv_TargetUnitGroups
end

local custom_unit_groups = {"EnemySquad", "Villains"}
g_AnyUnitGroups = { 
	["any"] = true, 
	["any merc"] = true, 
	["current unit"] = true, 
	["player mercs on map"] = true 
}

function RecalcGroups()
	if GetMap() == "" then return end
	
	local groups = GetUnitSpawnMarkerGroups()
	groups[#groups+1] = groups_separator
	local mercs = {}
	for k,v in pairs(UnitDataDefs) do
		if IsMerc(v) then
			mercs[#mercs+1] = k
		end
	end
	table.sort(mercs)
	table.iappend(groups, mercs)
	groups[#groups+1] = groups_separator
	
	local non_mercs = {}
	for k,v in pairs(UnitDataDefs) do
		if not IsMerc(v) then
			non_mercs[#non_mercs+1] = k
		end
	end
	table.sort(non_mercs)
	table.iappend(groups, non_mercs)
	table.iappend(groups, custom_unit_groups)
	
	gv_UnitGroups = groups
	
	gv_TargetUnitGroups = table.keys2(g_AnyUnitGroups, "sorted")
	table.iappend(gv_TargetUnitGroups, groups)
end

function TFormat.GetNumAliveUnitsInGroup(context, groupName)
	return GetNumAliveUnitsInGroup(groupName)
end

function GetNumAliveUnitsInGroup(group)
	local num = 0
	for _, obj in ipairs(Groups and Groups[group]) do
		if IsKindOf(obj, "Unit") and not obj:IsDead() then
			num = num + 1
		end
	end
	return num
end

OnMsg.NewMapLoaded = RecalcGroups
OnMsg.GameExitEditor = RecalcGroups

function OnMsg.UnitDied()
	ObjModified(gv_Quests)
end

GameVar("DeadGroupsInSectors", {})
function UpdateDeadGroups(groups)
	local deadGroups = DeadGroupsInSectors[gv_CurrentSectorId] or {}
	for _, group in ipairs(groups) do
		local allDead = GetNumAliveUnitsInGroup(group) == 0
		if allDead then
			deadGroups[group] = "all"
		else
			deadGroups[group] = "any"
		end
	end
	DeadGroupsInSectors[gv_CurrentSectorId] = deadGroups
end

function OnMsg.UnitDieStart(unit)
	UpdateDeadGroups(unit.Groups)
end

function OnMsg.VillainDefeated(unit)
	UpdateDeadGroups(unit.Groups)
end

function OnMsg.GatherFXActions(list)
	table.insert(list, "StepRun")
	table.insert(list, "StepWalk")
	table.insert(list, "StepRunCrouch")
	table.insert(list, "StepRunProne")

	table.insert(list, "Interact")
	for i,combat_action in ipairs(Presets.CombatAction.Interactions) do
		table.insert(list, combat_action.id)
	end
end

function OnMsg.GatherFXActors(list)
	table.insert(list, "Unit")
end

function Unit:AutoRemoveCombatEffects()
	local effect_ids = table.map(self.StatusEffects or empty_table, "class")
	for _, id in ipairs(effect_ids) do
		local def = CharacterEffectDefs[id]
		if def and def.RemoveOnEndCombat then
			self:RemoveStatusEffect(id, "all")
		end
	end
end

local ExitCombatUninterruptable = {
	["Visit"] = true,
	["EnterMap"] = true,
	["Cower"] = true,
}

function OnMsg.CombatEnd(combat)
	MapForEach("map", "Unit", function(unit)
		unit:AutoRemoveCombatEffects()
		if not unit:IsDead() and g_Overwatch[unit] and (not g_Overwatch[unit].permanent or unit.team.control ~= "UI") then
			unit:InterruptPreparedAttack()
			unit:RemovePreparedAttackVisuals()
		end
		if not unit:IsDead() or unit.immortal then
			local overwatch = g_Overwatch[unit]
			if not ExitCombatUninterruptable[unit.command] then
				if overwatch and overwatch.permanent then
					-- only check for reload
					unit:UpdateNumOverwatchAttacks()
					CreateGameTimeThread(Unit.AutoReload, unit)
				else
					unit:InterruptCommand("ExitCombat")
				end
			end
		end
	end)
end

function Unit:IsAdjacentTo(other, check_pos)
	local x, y, z
	if check_pos then
		x, y, z = PosToGridCoords(check_pos:xyz())
	else
		x, y, z = self:GetGridCoords()
	end
	
	local ox, oy, oz = other:GetGridCoords()

	return abs(x - ox) <= 1 and abs(y - oy) <= 1 and abs(z - oz) <= 1
end

function Unit:CanSurround(other, check_pos)
	-- side
	if not self:IsOnEnemySide(other) or self:IsDead() or self:IsDowned() then
		return false
	end
	
	-- status effects
	if self:HasStatusEffect("Suppressed") then
		return false
	end
	
	-- Not valid gameplay wise, but happens in some rare cases and fires asserts down the line.
	local pos = check_pos or self:GetPos()
	if other:GetPos() == pos then
		return false
	end
	
	-- visibility
	if check_pos then
		-- checking from another position, use CheckLOS
		if not CheckLOS(other, self, self:GetSightRadius()) then
			return false
		end
	else
		-- checking from current position, can use precomputed visibility
		if not HasVisibilityTo(self, other) then
			return false
		end
	end
	
	-- weapon range
	local adjacent = self:IsAdjacentTo(other, check_pos)
	local in_range = false
	local w1, w2, weapons = self:GetActiveWeapons()
	for _, weapon in ipairs(weapons) do
		if IsKindOf(weapon, "Firearm") or (IsKindOf(weapon, "MeleeWeapon") and weapon.CanThrow) then
			-- heavy weapons are Firearms and go here too
			in_range = in_range or other:GetDist(pos) <= weapon.WeaponRange * const.SlabSizeX
		elseif IsKindOf(weapon, "MeleeWeapon") then
			in_range = in_range or adjacent
		end
	end
	
	return in_range
end

function Unit:IsSurrounded(unitReplace)
	if not g_Visibility or not g_Combat or self:IsDead() then
		return
	end
	
	local pos = unitReplace and unitReplace[self] or self:GetPos()
	local enemy_pos = {}
	local angle = 120*60
	local cosa = MulDivRound(cos(angle), guim*guim, 4096)

	for _, team in ipairs(g_Teams) do
		if team.side ~= "neutral" then
			for _, u in ipairs(team.units) do
				if u:CanSurround(self, unitReplace and unitReplace[u]) then
					enemy_pos[#enemy_pos + 1] = unitReplace and unitReplace[u] or u:GetPos()
				end
			end
		end
	end
	if #enemy_pos < 2 then
		return
	end
	local pts = ConvexHull2D(enemy_pos)

	for i = 1, #pts - 1 do
		local v1 = pts[i]:Equal2D(pos) and point30 or SetLen(pts[i] - pos, guim)
		for j = i + 1, #pts do
			local v2 = pts[j]:Equal2D(pos) and point30 or SetLen(pts[j] - pos, guim)
			local dp = Dot2D(v1, v2)
			if dp < cosa then
				return true
			end
		end
	end	
end

function InterpolateCoverEffect(coverage, full_value, exposed_value)
	local threshold = 40
	if coverage >= 80 then
		return full_value
	elseif coverage < threshold then
		return exposed_value
	end
	return exposed_value + MulDivRound(full_value - exposed_value, coverage - threshold, threshold)
end

function Unit:ApplyHitDamageReduction(hit, weapon, hit_body_part, ignore_cover, ignore_armor, record_breakdown)
	local damage = hit.damage or 0
	hit.damage = damage
	local weapon_pen_class = weapon:HasMember("PenetrationClass") and weapon.PenetrationClass or 1
	self:ForEachItem("Armor", function(item, slot, left, top, hit, ignore_armor, record_breakdown, weapon_pen_class)
		if hit.damage > 0 and slot ~= "Inventory" and item.ProtectedBodyParts and item.ProtectedBodyParts[hit_body_part] then
			local dr, degrade, pierced
			if not ignore_armor and item.Condition > 0 then
				dr = item.DamageReduction
				degrade = item.Degradation
				if weapon_pen_class < item.PenetrationClass then
					dr = dr + item.AdditionalReduction
					degrade = MulDivRound(degrade, const.Combat.ArmorDegradePercent, 100)
				else
					pierced = true
				end
			else
				pierced = true
			end
			-- scale DR down on poor condition
			dr = MulDivRound(dr or 0, Min(100, 50 + item.Condition), 100)

			local scaled = hit.damage * (100 - dr)
			local result = scaled / 100
			if pierced and scaled % 100 > 0 then
				-- round the resulting damage up when pierced only
				result = result + 1
			end

			if record_breakdown then
				if pierced then
					record_breakdown[#record_breakdown + 1] = { name = T{191288543859, "<em><DisplayName></em> (Pierced)", item}, value = -dr }
				else
					record_breakdown[#record_breakdown + 1] = { name = T{516752639882, "<em><DisplayName></em>", item}, value = -dr }
				end
			end

			hit.damage = Min(hit.damage, result)
			if not hit.armor_decay then hit.armor_decay = {} end
			if not hit.armor_pen then hit.armor_pen = {} end
			hit.armor_decay[item] = Min(item.Condition, degrade or 0)
			if pierced then
				hit.armor_pen[item] = true
			end
		end
	end, hit, ignore_armor, record_breakdown, weapon_pen_class)

	local armor_prevented = damage - hit.damage

	-- HoldPosition perk damage reduction
	if HasPerk(self, "HoldPosition") and (g_Overwatch[self] or g_Pindown[self]) then
		local statPercent = CharacterEffectDefs.HoldPosition:ResolveValue("percentHealth")
		local percent_reduction = MulDivRound(self.Health, statPercent, 100)
		if record_breakdown then record_breakdown[#record_breakdown + 1] = { name = CharacterEffectDefs.HoldPosition.DisplayName, value = -percent_reduction } end
		hit.damage = Max(0, MulDivRound(hit.damage, 100 - percent_reduction, 100))
	end

	local armor = next(hit.armor_decay)
	hit.armor = armor and armor.DisplayName
	hit.armor_prevented = armor_prevented
end

function Unit:IsArmored(target_spot_group)
	if self:IsDead() then return false end
	local armorFound = false
	self:ForEachItem("Armor", function(item, slot)
		if slot ~= "Inventory" and (not target_spot_group or item.ProtectedBodyParts and item.ProtectedBodyParts[target_spot_group]) then 
			armorFound = item
			return "break"
		end
	end)
	
	local iconName = false
	if armorFound and armorFound.PenetrationClass > 1 then
		local classId = PenetrationClassIds[armorFound.PenetrationClass]
		iconName = classId:lower() .. "_armor"
	end
	
	return armorFound, iconName, "UI/Hud/"
end

function Unit:ApplyDamageAndEffects(attacker, damage, hit, armor_decay)
	if self:IsDead() or not IsValid(self) then return end

	if damage and damage > 0 or hit.setpiece then
		self:TakeDamage(damage or 0, attacker, hit)	
	end
	
	local invulnerable = self:IsInvulnerable()
	if not invulnerable then
		local effects = hit.effects
		if type(effects) == "string" and effects ~= "" then
			self:AddStatusEffect(effects)
		else
			for _, effect in ipairs(effects) do
				if effect and effect ~= "" then
					self:AddStatusEffect(effect)
				end
			end
		end
	end
	
	-- blood/soot stains
	local was_wounded = self:HasStatusEffect("Wounded")
	if hit.direct_shot then -- bullet-simulated firearm attacks
		local spot, params = CalcStainParamsFromShot(self, attacker, hit)
		if spot then
			assert(not params or type(params) == "table")
			self:AddStain("Blood", spot, params)
		end
	elseif not was_wounded then
		-- pick a spot and save it as effect value for the Wounded status to use if it gets applied
		local spot
		if hit.melee_attack then
			spot = GetRandomStainSpot(hit.spot_group)
		else
			spot = GetRandomStainSpot()
		end
		if spot then
			self:SetEffectValue("wounded_stain_spot", spot)
		end
	end
	
	-- cleanup wounded_stain_spot
	self:SetEffectValue("wounded_stain_spot", nil)
	
	-- add soot from explosions (if there's no blood)
	if hit.explosion and not self:HasStainType("Blood") then
		local spot = GetRandomStainSpot()
		self:AddStain("Soot", spot)
	end
		
	if not invulnerable then
		local change = false
		for item, degrade in pairs(armor_decay) do
			item.Condition = self:ItemModifyCondition(item, - degrade)
			if IsKindOf(item, "TransmutedItemProperties") and item.RevertCondition=="damage" then
				item.RevertConditionCounter = item.RevertConditionCounter-1
				if item.RevertConditionCounter== 0 then
					local slot_name = self:GetItemSlot(item)
					local new, prev = item:MakeTransmutation("revert")
					armor_decay[new] = degrade
					armor_decay[item] = false
					self:RemoveItem(slot_name, item)
					self:AddItem(slot_name, new)					
					DoneObject(prev)
					change = true
				end
			end	
		end
		if change then
			self:UpdateOutfit()
		end
	end
end

function Unit:SwapActiveWeapon(action_id, cost_ap)
	local igi = GetInGameInterfaceModeDlg()
	if IsKindOf(igi, "IModeCombatBase") and igi.attacker == self then
		InvokeShortcutAction(igi, "ExitAttackMode", igi)
	end

	if self.current_weapon == "Handheld A" then
		self.current_weapon = "Handheld B"
	else
		self.current_weapon = "Handheld A"
	end

	self:OnSetActiveWeapon(action_id, cost_ap)
end

function Unit:OnSetActiveWeapon(action_id, cost_ap)
	if not self.current_weapon then return end
	if HasPerk(self, "Scoundrel") and g_Combat then
		self:ActivatePerk("Scoundrel")
		PlayVoiceResponse(self, "Scoundrel")
	end
	if GameTimeAdvanced then
		if g_Overwatch[self] and not self:FindWeaponInSlotById(self.current_weapon, g_Overwatch[self].weapon_id) or
			g_Pindown[self] and not self:FindWeaponInSlotById(self.current_weapon, g_Pindown[self].weapon_id) or
			self.prepared_bombard_zone and not self:FindWeaponInSlotById(self.current_weapon, self.prepared_bombard_zone.weapon_id)
		then
			self:InterruptPreparedAttack()
		end
	end
	self:UpdateOutfit(self.Appearance)
	self:RecalcUIActions()
	--self.lastFiringMode = false
	self:SetAimTarget(false, false)
	if not cost_ap or cost_ap == 0 then
		-- if the action was free we still want the UI to reflect possible differences
		Msg("UnitAPChanged", self, action_id) 
	end
	Msg("UnitSwappedWeapon", self)
	ObjModified(self)
end

function Unit:StartAI(debug_data, forced_behavior)
	if not IsValid(self) or self:IsDead() or self.ai_context or self:HasStatusEffect("Unconscious") then
		return
	end
	AIReloadWeapons(self)
	
	local proto_context = {}
	self:SelectArchetype(proto_context)
	
	--local context = AICreateContext(self, proto_context)
	--local archetype = context.archetype
	local archetype = self:GetArchetype()
	
	local scores, available = {}, {}
	local total = 0

	AIUpdateBiases()
	for i, behavior in ipairs(archetype.Behaviors) do
		local weight_mod, disable, priority
		if behavior:MatchUnit(self) then
			weight_mod, disable, priority = AIGetBias(behavior.BiasId, self)
			priority = priority or behavior.Priority
		else
			weight_mod, disable, priority = 0, true, false
		end

		if debug_data then
			debug_data.behaviors = debug_data.behaviors or {}
			debug_data.behaviors[i] = {
				name = behavior:GetEditorView(),
				priority = priority,
				disable = disable,
				behavior = behavior,
				index = i,
			}
		end

		if not disable then
			local score = MulDivRound(behavior:Score(self, proto_context, debug_data), weight_mod, 100)
			if debug_data then
				debug_data.behaviors[i].score = score
			end
			if score > 0 then
				if priority and not forced_behavior then
					forced_behavior = behavior
					break
				end
				scores[#scores + 1] = score
				available[#available + 1] = behavior
				total = total + score
			end
		end
	end
	
	if total == 0 and not forced_behavior then 
		printf("unit of %s archetype failed to select a behavior!", archetype.id)
		return
	end
	
	local roll = InteractionRand(total, "AIBehavior", self)
	local selected
	if not forced_behavior then
		for i, behavior in ipairs(available) do
			local score = scores[i]
			if roll <= score then
				selected = behavior
				break
			end
			roll = roll - score
		end
	end
	
	if self.ai_context then
		self.ai_context.behavior = forced_behavior or selected or available[#available]
	else
		proto_context.behavior = forced_behavior or selected or available[#available]
		AICreateContext(self, proto_context)
	end
	if self.ai_context.behavior then
		self.ai_context.behavior:OnStart(self)
	end
	return true
end

function UpdateSurrounded()	
	for _, unit in ipairs(g_Units) do
		if unit:IsSurrounded() then
			unit:AddStatusEffect("Flanked")
		else
			unit:RemoveStatusEffect("Flanked")
		end
	end
end

function RollSkillCheck(unit, skill, modifier, add)
	assert(IsKindOf(unit, "UnitPropertiesStats"))
	
	modifier = modifier or 100
	add = add or 0
	
	local roll = 1 + unit:Random(100)
	--adjust roll based on diff
	local adjustRoll = GameDifficulties[Game.game_difficulty]:ResolveValue("rollSkillCheckBonus") or 0
	roll = roll + adjustRoll
	roll = Min(roll, 95)
	
	local value = MulDivRound(unit[skill], modifier, 100) + add
	local pass = roll < value or CheatEnabled("SkillCheck")
	
	--CombatLog("debug", 
	local t_res = pass and Untranslated("<em>Pass</em>") or Untranslated("<em>Fail</em>")
	local meta = unit:GetPropertyMetadata(skill)
	local t_skill = meta.name
	if modifier ~= 100 then
		if add > 0 then
			t_skill = T{816405633181, "<percent(n1)> <skill>+<n2>", n1 = modifier, n2 = add, skill = meta.name}
		elseif add < 0 then
			t_skill = T{656059859333, "<percent(n1)> <skill><n2>", n1 = modifier, n2 = add, skill = meta.name}
		else
			t_skill = T{570928040607, "<percent(number)> <skill>", number = modifier, skill = meta.name}
		end
	elseif add > 0 then
		t_skill = T{481345361355, "<skill>+<number>", number = add, skill = meta.name}
	elseif add < 0 then
		t_skill = T{945399039468, "<skill><number>", number = add, skill = meta.name}
	end
	
	CombatLog("debug", T{Untranslated("<em><name><em> Skill check (<em><skill></em>) <roll>/<target>: <result>"), 
		name = unit:GetLogName(),
		skill = t_skill,
		roll = roll, 
		target = value,
		result = t_res,
	})
	return pass
end

function SkillCheck(unit, skill, threshold,dont_report_fails)
	if not unit or not IsKindOf(unit, "UnitPropertiesStats") then return "error" end
	local stat = unit[skill]
	if not stat then return "error" end
	if threshold <= stat or CheatEnabled("SkillCheck") then
		CombatLog("debug", "(success) " .. unit.session_id .. " " .. skill.. " check (" .. stat.. " / " ..threshold .. ")")
		PlayFX("SkillCheck", "success", unit, skill)
		return "success", stat - threshold, stat
	end	
	if not dont_report_fails then
		PlayFX("SkillCheck", "fail", unit, skill)
		CombatLog("debug", "(fail) " .. unit.session_id .." " .. skill.. " check (" .. stat.. " / " ..threshold .. ")")
	end
	return "fail", threshold - stat, stat
end

function SpawnUnit(class, session_id, pos, angle, groups, spawner, entrance)
	session_id = session_id or class
	NetUpdateHash("SpawnUnit", class, session_id, pos)
	local unit_data = CreateUnitData(class, session_id, InteractionRand(nil, "Satellite"))

	local unit_group = UnitDataDefs[unit_data.class].group
	local unit = Unit:new{ 
		unitdatadef_id = unit_data.class,
		group = unit_group,
		session_id = session_id,
		spawner = spawner,
		entrance_marker = entrance,
	}

	AddToGlobalUnits(unit)

	for _, group in ipairs(groups) do
		unit:AddToGroup(group)
	end

	if angle then
		unit:SetAngle(angle)
	end
	if pos then
		unit:SetPos(pos)
	end

	if unit:IsNPC() and not unit.dummy then
		if IsKindOf(spawner, "UnitMarker") then
			for _, effect in ipairs(spawner.status_effects) do
				if CharacterEffectDefs[effect] then
					unit:AddStatusEffect(effect)
				end
			end
		end
		if IsKindOf(spawner, "GridMarker") and spawner.Suspicious or IsKindOf(entrance, "GridMarker") and entrance.Suspicious then
			unit:AddStatusEffect("HighAlert")
			if not spawner or spawner.Side ~= "neutral" then
				unit:AddStatusEffect("Unaware")
			end
		else
			local data = gv_UnitData[session_id]
			local squad_idx = data and data.Squad and table.find(g_SquadsArray, "UniqueId", data.Squad)
			local squad = squad_idx and g_SquadsArray[squad_idx]
			if squad and squad.militia then
				unit:AddStatusEffect("HighAlert")
			elseif not spawner or spawner.Side ~= "neutral" then
				unit:AddStatusEffect("Unaware")
			end
		end
	end
	unit:SetTargetDummyFromPos()

	return unit
end

function ValidateUnitGroupForEffectExec(group, effect, trigger_obj)
	local units = Groups[group]
	if Platform.developer and GameState.entered_sector and not units then
		local trigger_obj_idx = 1
		local errs = {}
		local sector_ids, effect_classes = {}, {}
		
		local function addErr(effect, parents, obj)
			if effect:HasMember("Group") and effect.Group == group then
				if obj == trigger_obj then
					trigger_obj_idx = #errs + 1
				end
				if IsKindOf(obj, "QuestsDef") then
					errs[#errs + 1] = {obj, string.format("Effect %s with invalid group %s in quest %s", effect.class, group, obj.id)}
				elseif IsKindOf(obj, "SatelliteSector") then
					sector_ids[#sector_ids + 1] = obj.Id
					effect_classes[#effect_classes + 1] = effect.class
				elseif IsKindOf(obj, "GridMarker") then
					errs[#errs + 1] = {obj, string.format("Effect %s with invalid group %s in marker", effect.class, group)}
				end
			end
		end
		
		-- check quest effects
		ForEachPresetInCampaign("QuestsDef", function(quest)
			if quest.TCEs and next(quest.TCEs) then
				for _, tce in ipairs(quest.TCEs) do
					tce:ForEachSubObject("Effect", addErr, quest)
				end
			end
		end)
		
		-- check sector effects
		local campaign_preset = Game.Campaign and CampaignPresets[Game.Campaign]
		for _, sector in ipairs(campaign_preset and campaign_preset.Sectors) do
			for _, event in ipairs(sector.Events) do
				sector:ForEachSubObject("Effect", addErr, sector)
			end
		end
		if next(sector_ids) then
			errs[#errs + 1] = {campaign_preset, string.format("Effects - %s - with invalid group %s in sectors: %s", table.concat(effect_classes, ", "), group, table.concat(sector_ids, ", "))}
		end
		
		--check grid marker effects
		MapForEachMarker("GridMarker", nil, function(marker)
			marker:ForEachSubObject("Effect", addErr, marker)
		end)
		
		errs[1], errs[trigger_obj_idx] = errs[trigger_obj_idx], errs[1]
		for _, err in ipairs(errs) do
			StoreErrorSource(err[1], err[2])
		end
	end
	return units or empty_table
end

OnMsg.VisibilityUpdate = UpdateSurrounded
OnMsg.CombatApplyVisibility = UpdateSurrounded
OnMsg.CombatStart = UpdateSurrounded
OnMsg.CombatEnd = UpdateSurrounded

function OnMsg.CombatStart(dynamic_data)
	local transfer_keys = {
		"hmg_emplacement",
		"spent_ap",
		"PrisonDoor",
		"CellLeaveBanters"
	}

	for _, unit in ipairs(g_Units) do
		if unit.team.side == "neutral" and not unit.behavior then
			unit:SetBehavior("GoBackAfterCombat", {unit:GetPos()})
		end
		if not dynamic_data then
			local values = {}
			for i, key in ipairs(transfer_keys) do
				values[i] = unit:GetEffectValue(key)				
			end
			unit.effect_values = nil -- reset effect data on combat start
			for i, key in ipairs(transfer_keys) do
				if values[i] ~= nil then
					unit:SetEffectValue(key, values[i])
				end					
			end
			if unit.carry_flare then
				unit:RoamDropFlare()
			end
		end
		unit.marked_target_attack_args = nil	-- invalid in combat
		unit.neutral_retal_attacked = nil
	end
end

DefineClass.DummyUnit = {
	__parents = { "AppearanceObject" },
	flags = { gofPermanent = true, gofUnitLighting = false },
	properties = {
		{category = "Dummy Unit", id = "UnitLighting", name = "Unit Lighting", editor = "bool",
			default = false,
		},
		{category = "Dummy Unit", id = "FreezePhase", name = "Freeze Phase", editor = "number",
			default = false, slider = true, min = 0,
			max = function(obj)
				return GetAnimDuration(obj:GetEntity(), obj.anim) - 1
			end,
			help = "The unit will be freezed at this frame.",
		},
	},
	entity = "Male",
	Appearance = "Raider_01",
}

function DummyUnit:GameInit()
	self:UpdateFreezePhase()
end

function DummyUnit:OnEditorSetProperty(prop_id, old_value, ged)
	if prop_id == "FreezePhase" or prop_id == "anim" then
		self:UpdateFreezePhase()
	end
end

function DummyUnit:UpdateFreezePhase()
	local phase = self:GetProperty("FreezePhase")
	if phase then
		self:SetAnimPose(self.anim, phase)
		self:SetAnimSpeedModifier(0)
	else
		self:SetAnimSpeedModifier(1000)
	end
end

-- NOTE: Level Designers are setting the anim through StateText which gets overridden by 'anim' property
function DummyUnit:SetStateText(state)
	AppearanceObject.SetStateText(self, state)
	self:SetProperty("anim", state)
end

function DummyUnit:SetUnitLighting(value)
	if value then
		self:SetHierarchyGameFlags(const.gofUnitLighting)
	else
		self:ClearHierarchyGameFlags(const.gofUnitLighting)
	end
	self:DestroyRenderObj()
end

function DummyUnit:GetUnitLighting(value)
	return self:GetGameFlags(const.gofUnitLighting) ~= 0
end

function ErnyTown_HangUnit(group_id)
	local group = Groups[group_id]
	local units = {}
	for _, o in ipairs(group) do
		if IsKindOf(o, "Unit") then
			table.insert(units, o)
		end
	end	
	if #units ~= 1 then
		StoreErrorSource(point30, "There should be exactly one unit of the group " .. group_id)
		return
	end
	local unit = units[1]
	unit:SetCommand("Hang")
	unit:SetGroups(false)
end

function OnMsg.ValidateMap()
	if Game and not g_IdleAnimActionStances then
		FillIdleAnimActionsAndStances()
	end
end

function OnMsg.ChangeMapDone(map)
	if IsModEditorMap(map) and not g_IdleAnimActionStances then
		FillIdleAnimActionsAndStances()
	end
end

if FirstLoad then
	g_IdleAnimActionStances = false
end

local function GetAllEntitiesValidAnimations()
	local dummy = PlaceObject("Unit", {
		NetUpdateHash = empty_func,
		IsSyncObject = function(self) return false end,
	})
	dummy:ClearGameFlags(const.gofSyncObject)
	dummy:SetCommand(false)
	dummy:SetPos(point30)
	
	local anims = {}
	for id, app in sorted_pairs(AppearancePresets) do
		if app.Body then
			dummy:ApplyAppearance(AppearancePresets[id])
			if IsValidEntity(dummy:GetEntity()) then
				dummy:SetState("idle")
				local dummy_anims = ValidAnimationsCombo(dummy)
				for _, a in ipairs(dummy_anims) do
					anims[a] = true
				end
			end
		end
	end
	DoneObject(dummy)
	
	return anims
end

function FillIdleAnimActionsAndStances()
	g_IdleAnimActionStances = {
		no_weapon = {g_StanceActionDefault, [g_StanceActionDefault] = {g_StanceActionDefault}},
		weapon = {g_StanceActionDefault, [g_StanceActionDefault] = {g_StanceActionDefault}}
	}
	
	local anims = GetAllEntitiesValidAnimations()
	for a, _ in sorted_pairs(anims) do
		local prefix, stance, action = string.match(a, "(.*)_(.*)_(.*)")
		if prefix and stance and action then
			local key = prefix == "civ" and "no_weapon" or "weapon"
			table.insert_unique(g_IdleAnimActionStances[key], stance)
			g_IdleAnimActionStances[key][stance] = g_IdleAnimActionStances[key][stance] or {g_StanceActionDefault}
			table.insert_unique(g_IdleAnimActionStances[key][stance], action)
		end
	end
end

function GetIdleAnimStances(use_weapons)
	assert(g_IdleAnimActionStances)
	return g_IdleAnimActionStances[use_weapons and "weapon" or "no_weapon"]
end

function GetIdleAnimStanceActions(use_weapons, stance)
	assert(g_IdleAnimActionStances)
	return g_IdleAnimActionStances[use_weapons and "weapon" or "no_weapon"][stance]
end

function Unit:ResolveUIAction(idx)
	local id = self.ui_actions and self.ui_actions[idx]
	return id and self.ui_actions[id] and CombatActions[id]
end

function Unit:IsAware(check_pending)
	if self.team and self.team.side == "neutral" or self.command == "Die" or self:IsDead() then
		return false
	end
	local status_effects = self.StatusEffects
	if check_pending then
		if self.pending_aware_state == "aware" or self.pending_aware_state == "surprised" or status_effects["Surprised"] then
			return true
		end
	end
	return not status_effects["Unaware"] and not status_effects["Suspicious"] and not status_effects["Surprised"]
end

function Unit:IsSuspicious()
	if self:IsDead() or self.command == "Die" then return false end
	return self:HasStatusEffect("Suspicious")
end

function Unit:AddToInventory(item_id, amount, callback)
	if not item_id then return 0 end
	amount = amount or 1
	local unit_amount = 0	
	self:ForEachItemInSlot("Inventory", "InventoryStack", 
		function(curitm, slot_name, item_left, item_top)
		   if curitm and item_id and curitm.class == item_id and curitm.Amount < curitm.MaxStacks then
				local to_add = Min(curitm.MaxStacks - curitm.Amount, amount)
				curitm.Amount =curitm.Amount + to_add
				Msg("InventoryAddItem", self, curitm, to_add)
				amount = amount - to_add			
				unit_amount = unit_amount + to_add
				if amount <= 0 then
					if callback then
						callback(self, curitm, unit_amount)
					end
					return "break"
				end
			end
		end)
	
	
	local itm
	while amount > 0 do			 
		local item = PlaceInventoryItem(item_id) 
		local is_stack = IsKindOf(item, "InventoryStack")
		
		if self:AddItem("Inventory", item) then 
			local to_add = 1
			if is_stack then
				to_add = Min(item.MaxStacks, amount) 
				item.Amount = to_add 
			end	
			unit_amount = unit_amount + to_add
			amount = amount - to_add
			unit_amount = unit_amount + to_add
			Msg("InventoryAddItem", self, item, to_add)
			itm =  item
		else
			DoneObject(item)
			break
		end				
	end		
	if callback and itm and unit_amount>0 then
		callback(self, itm, unit_amount)
	end
	ObjModified(self)

	return amount
end

-- Drop a container with a new item created from item_id.
function Unit:DropItemContainer(item_id, amount, callback)
	if amount <= 0 then return end
	local item = PlaceInventoryItem(item_id)
	local is_stack = IsKindOf(item, "InventoryStack")
	if is_stack then
		item.Amount = amount
	end

	local container = GetDropContainer(self, false,item )
	if container then
		local pos, res = container:AddItem("Inventory", item)
		if pos and callback then
			callback(self, item, amount)
		end
	end
end

-- Add already generated items (from loot table) into a container and drop it. Stack them if possible.
function Unit:DropItemsInContainer(items, callback)
	local container = GetDropContainer(self)
	if not container then return end
	for i = #items, 1, -1 do
		local item = items[i]
		if not container:CanAddItem("Inventory", item) then
			container = GetDropContainer(self, false, item)
		end
		local pos, reason = container:AddItem("Inventory", item)
		if pos then
			if callback then
				callback(self, item, IsKindOf("InventoryStack") and item.Amount or 1)
			end
			table.remove(items, i)
		end
	end	
end

function Unit:SetHighlightReason(reason, enable)
	self.highlight_reasons = self.highlight_reasons or {}
	self.highlight_reasons[reason] = enable
	
	self:UpdateHighlightMarking()

	if self.session_id then
		ObjModified(self.session_id .. "_combat_badge")
	end
	if reason == "deploy_predict" and self.ui_badge then
		self.ui_badge:SetVisible(not enable, "deploy_predict")
	end
end

function Unit:UpdateHighlightMarking() 
	if WaitRecalcVisibility then return end

	local marking = false

	-- if the unit was set invisible by visibility logic we dont want to mark it, as it would show it
	if not self.visible or IsSetpiecePlaying() or CheatEnabled("IWUIHidden") then
		marking = -1
	end
	
	-- during combat, only show marking of playing
	if not marking then
		local pov_team = GetPoVTeam()
		local enemyTurn = g_Combat and g_Teams[g_CurrentTeam] ~= pov_team
		local playing = IsMerc(self) or (g_AIExecutionController and table.find(g_AIExecutionController.currently_playing, self)) -- if merc skip  this check so we show hard to see mercs
		if enemyTurn and not playing then
			marking = -1
		end
	end
	
	if not marking then
		local reasons = self.highlight_reasons
		if reasons["dark voxel"] then
			marking = 3
		elseif reasons["area target"] then
			marking = 3
		elseif reasons["melee"] then
			marking = 3
		elseif reasons["melee-target"] then
			marking = 3
		elseif reasons["bandage-target"] then
			marking = 0
		elseif reasons["concealed"] then
			if HasThermalVision(Selection) then
				marking = 10
			else
				marking = 9
			end
		elseif reasons["obscured"] then
			marking = 7
		elseif reasons["visibility"] then
			local pov_team = GetPoVTeam()
			if pov_team:IsEnemySide(self.team) then
				local enemyTurn = g_Combat and g_Teams[g_CurrentTeam] ~= pov_team
				local playing = g_AIExecutionController and table.find(g_AIExecutionController.currently_playing, self)
				
				local seen = enemyTurn or playing
				if not seen then
					for _, unit in ipairs(Selection) do
						if HasVisibilityTo(unit, self) then
							seen = true
							break
						end
					end
				end
				marking = seen and 3 or 1
			elseif reasons["faded"] or g_Combat and not g_Combat:ShouldEndCombat() then -- ally and neutral only get marking in conflict unless they're walking in the air
				if pov_team:IsAllySide(self.team) then
					marking = 0
				else -- neutral
					marking = 2
				end
			end
		elseif reasons["deploy_predict"] then
			marking = 5
		elseif reasons["darkness"] then
			marking = 8
		elseif reasons["can_be_interacted"] then
			marking = 11
		end
	end

	marking = marking or -1
	self:SetObjectMarking(marking)
	if marking < 0 then
		self:ClearHierarchyGameFlags(const.gofObjectMarking)
	else
		self:SetHierarchyGameFlags(const.gofObjectMarking)
	end
end

const.utWellRested = -1
const.utNormal = 0
const.utTired = 1
const.utExhausted = 2
const.utUnconscious = 3

UnitTirednessEffect = {
	[const.utWellRested] = "WellRested",
	[const.utNormal] = "Default",
	[const.utTired] = "Tired",
	[const.utExhausted] = "Exhausted",
	[const.utUnconscious] = "Unconscious",
}

function TFormat.tiredness(context_obj, value)
	local effect = UnitTirednessEffect[value]
	if effect and g_Classes[effect] then
		return g_Classes[effect].DisplayName
	elseif effect == "Default" then
		return T(714191851131, "Normal")
	end
	return ""
end

function UnitTirednessComboItems()
	local items = {}
	for k, v in sorted_pairs(UnitTirednessEffect) do
		items[#items + 1] = { name = v, value = k }
	end
	return items
end

function OnMsg.UnitRelationsUpdated()
	for _, unit in ipairs(g_Units) do
		unit:UpdateMeleeTrainingVisual()
	end
end

-- sort units map by pos
function SortUnitsMap(units_map) 
	if not units_map or not next(units_map) then return units_map end
	local first_key = next(units_map)
	if next(units_map, first_key) == nil then 
		return {{id = first_key.session_id, unit = first_key, data = units_map[first_key]}}
	end

	local positions = {}
	for unit, data in pairs(units_map) do
		if IsValid(unit) then
			positions[#positions + 1] = {id = unit.session_id, unit = unit, data = data}		
		end
	end
	table.sortby(positions, "id")
	return positions
end

function Unit:GetBodyParts(attack_weapon)
	local list = Presets.TargetBodyPart.Default
	if self.species == "Human" then
		local head = list.Head
		if IsKindOf(attack_weapon, "MeleeWeapon") then
			head = list.Neck
		end
		return { head, list.Arms, list.Torso, list.Groin, list.Legs } 
	end
	return { list.Head, list.Torso, list.Legs } 
end

function Unit:ShowMishapNotification(action)
	if self.team.player_team then
		local text = action:GetAttackWeapons(self).DisplayName
		HideTacticalNotification("playerAttack")
		ShowTacticalNotification("playerAttack", false, T{989807512852, "<attack> Mishap", attack = text})
	else
		local text = GetTacticalNotificationText("enemyAttack") or action:GetAttackWeapons(self).DisplayName
		HideTacticalNotification("enemyAttack")
		ShowTacticalNotification("enemyAttack", false, T{989807512852, "<attack> Mishap", attack = text})
	end
	CreateFloatingText(self, T(371973388445, "Mishap!"), "FloatingTextMiss")
end

function Unit:GetValidStance(target_stance, pos)
	if target_stance == "Prone" then
		local side = self.team and self.team.side or "player1"
		local pfclass = CalcPFClass(side, "Prone", self.body_type)
		if not GetPassSlab(pos or self, pfclass) then
			return "Crouch"
		end
	end
	return target_stance
end

function Unit:CanSwitchStance(toDoStance, args)
	--no stance switch available for machineguns 
	if self:IsStanceChangeLocked() then
		return false
	end
	--no stance switch for prone - addition checks
	local action
	if toDoStance == "Standing" then
		action = "StanceStanding"
	elseif toDoStance == "Crouch" then
		action = "StanceCrouch"
	elseif toDoStance == "Prone" then
		local unitOrGotoPos = args and args.goto_pos or self
		local in_water = terrain.IsWater(unitOrGotoPos) -- disable when all the units are in water
		if in_water then 
			return false, AttackDisableReasons.Water 
		end		
		local valid_stance = self:GetValidStance("Prone", unitOrGotoPos)
		if valid_stance ~= "Prone" then
			return false, AttackDisableReasons.Stairs
		end
		action = "StanceProne"
	end
	--no stance switch avaible for lack of ap
	local cost = CombatActions[action]:GetAPCost(self, args)
	if cost < 0 then 
		return false, "hidden" 
	end
	if not self:UIHasAP(cost, action) then 
		return false, GetUnitNoApReason(self)
	end
	return true
end

function Unit:IsStanceChangeLocked()
	if IsKindOf(self:GetActiveWeapons(), "MachineGun") and (self.behavior == "OverwatchAction" or self.combat_behavior == "OverwatchAction")then 
		return true
	end
	if self:GetBandageTarget() then -- bandaging other unit
		return true
	end
	
	return false
end

MapVar("g_AttackRevealQueue", false)

function Unit:AttackReveal(action, attack_args, results)
	local attacker = self
	local target = attack_args.target
	local killed = results.killed_units or empty_table
	if not g_Combat then
		g_AttackRevealQueue = {self}
	end
	if IsKindOf(target, "Unit") and not target:IsDead() and not table.find(killed, target) then
		if g_Combat then
			self:RevealTo(target)
		else
			g_AttackRevealQueue[#g_AttackRevealQueue + 1] = target
		end
	end
	for _, hit in ipairs(results) do
		local unit = IsKindOf(hit.obj, "Unit") and not hit.obj:IsIncapacitated() and hit.obj
		if unit and unit.team ~= self.team and not unit:IsDead() and not table.find(killed, unit) then
			if g_Combat then
				self:RevealTo(unit)
			else
				g_AttackRevealQueue[#g_AttackRevealQueue + 1] = unit
			end
		end
	end
end

function Unit:OnEnemySighted(other)
	--printf("%s has seen %s", unit.unitdatadef_id, other.unitdatadef_id)
	if HasPerk(self, "AlwaysReady") and 
		not self:HasStatusEffect("Hidden") and
		g_Combat and not g_Combat:ShouldEndCombat() and
		g_Teams[g_CurrentTeam] ~= self.team and
		not self:HasPreparedAttack() and
		not self:IsThreatened(nil, "overwatch")
	then	
		self:TryActivateAlwaysReady(other)
	end
end

function Unit:GetMoveAPCost(dest)
	if not dest or not (g_Combat or g_StartingCombat) then return 0 end
	
	local move_cost = 0
	local path = GetCombatPath(self)
	move_cost = path and path:GetAP(dest)
	if not move_cost then return -1 end
	
	return Max(0, move_cost - self.free_move_ap)
end

function Unit:HasNightVision()
	if HasPerk(self, "NightOps") then
		return true
	end
	local helm = self:GetItemInSlot("Head")
	return IsKindOf(helm, "NightVisionGoggles") and helm.Condition > 0
end

function NetSyncEvents.SetAutoFace(obj, auto_face)
	if not obj or obj.auto_face == auto_face then
		return
	end
	obj.auto_face = auto_face
	-- reorientation
	if auto_face
		and obj.command == "Idle"
		and obj.stance ~= "Prone"
		and not obj.interrupt_callback
		and not IsValidThread(obj.reorientation_thread)
	then
		obj.reorientation_thread = CreateGameTimeThread(function(obj)
			Sleep(obj:Random(500))
			if obj.auto_face
				and obj.command == "Idle"
				and (obj.stance == "Standing" or obj.stance == "Crouch")
				and not obj.interrupt_callback
			then
				obj:InterruptCommand("Idle")
			end
			obj.reorientation_thread = false
		end, obj)
	end
end

function OnMsg.SelectedObjChange()
	local obj = SelectedObj
	if not obj then
		return
	end
	if not obj.auto_face then
		return
	end
	if not (g_Combat and g_Teams and g_Teams[g_CurrentTeam] == obj.team) then
		return
	end
	if not obj:IsLocalPlayerControlled() then
		return
	end
	NetSyncEvent("SetAutoFace", obj, false)
end

function OnMsg.SelectionRemoved(obj)
	if not (g_Combat and g_Teams and g_Teams[g_CurrentTeam] == obj.team) then
		return
	end
	if not obj:IsLocalPlayerControlled() then
		return
	end
	if obj.stance == "Prone" then
		return
	end
	NetSyncEvent("SetAutoFace", obj, true)
end

function OnMsg:TurnEnded(team)
	for i, unit in ipairs(g_Teams[g_CurrentTeam].units) do
		unit.auto_face = true
	end
end

-- TargetDummy
DefineClass.TargetDummy = {
	__parents = { "Movable", "SyncObject", "AppearanceObject" },
	flags = {
		efUnit = true, efVisible = false, efSelectable = false, efWalkable = false, efCollision = false,
		efPathExecObstacle = false, efResting = false,
		efApplyToGrids = false, efShadow = false, efSunShadow = false, gofOnRoof = false,
	},
	__toluacode = empty_func,
	obj = false,
	stance = false,
	locked = false,
}
DefineClass.TargetDummyLargeAnimal = {
	__parents = { "TargetDummy" },
}

function TargetDummy:Init()
	local obj = self.obj
	if obj then
		self:ApplyAppearance(obj.Appearance)
		pf.SetGroundOrientOffsets(self, table.unpack(obj:GetGroundOrientOffsets()))
	end
	self:SetDestlockRadius(obj and obj:GetDestlockRadius() or 0)
	self:SetCollisionRadius(0)
	self:SetAnimSpeed(1, 0)
	Msg("NewTargetDummy", self) -- for debug visualization
end

-- disable setting efPathExecObstacle
TargetDummy.InitPathfinder = empty_func
TargetDummy.EnterPathfinder = empty_func
TargetDummy.EnterPathfinder = empty_func

function SavegameSectorDataFixups.ClearTargetDummies(sector_data)
	local spawn_data = sector_data.spawn
	while true do
		local idx = table.find(spawn_data, "TargetDummy")
		if not idx then
			break
		end
		table.remove(spawn_data, idx + 1) -- handle
		table.remove(spawn_data, idx)     -- TargetDummy
	end
end

function IsLastUnitInTeam(units)
	local lastStanding = false
	for _, unit in ipairs(units) do
		if not unit:IsDead() and not lastStanding then
			lastStanding = unit
		elseif not unit:IsDead() and lastStanding then
			return false
		end
	end
	return lastStanding
end

function SavegameSessionDataFixups.ExpFixup(data, metadata, lua_ver)
	local ud = data.gvars.gv_UnitData
	for _, data in pairs(ud) do
		if not data.Experience then
			local minXP = GetXPTable(data.StartingLevel)
			data.Experience = minXP
		end
		data:RemoveModifier("ExperienceBonus", "Experience")
	end
end

UndefineClass('AdditionalGroup')
DefineClass.AdditionalGroup = {
	__parents = { "PropertyObject" },
	properties = {
		{ id = "Weight", name = "Weight", editor = "number", min = 0, max = 100, default = 100, help = "Integer numbers.(0:never picked / 100:always picked)"},
		{ id = "Exclusive", name = "Mutually Exclusive", editor = "bool", default = false, 
		help = "If marked as exclusive, only one will be chosen from all marked as exclusive. NB: If only one is marked as exclusive and weight > 0, it will be ALWAYS picked." },
		{ id = "Name", name = "Name", editor = "text", default = "", help = "The name of the group." },
	},
}

function AdditionalGroup:EditorView()
	return string.format("AdditionalGroup %s", self.Name and self.Name ~= "" and ("- " .. self.Name) or "")
end

function Unit:IsConcealedFrom(observer)
	return GameState.Fog and not self.indoors and not IsCloser(self, observer, const.EnvEffects.FogUnkownFoeDistance)
end

function Unit:IsObscuredFrom(observer)
	return GameState.DustStorm and not self.indoors and not IsCloser(self, observer, const.EnvEffects.DustStormUnkownFoeDistance)
end

function HasThermalVision(units)
	for _, unit in ipairs(units) do
		local _, _, weapons = unit:GetActiveWeapons()
		for _, weapon in ipairs(weapons) do
			if weapon:HasComponent("IgnoreConcealAndObscure") then
				return true
			end
		end
	end
end

function Unit:UIObscured()
	local side = self.CurrentSide or (self.team and self.team.side)
	if not side or side == "player1" or side == "player2" or side == "ally" then
		return false
	end
	if not GameState.DustStorm then
		return false
	end

	local units = Selection or empty_table
	if #units == 0 then
		local team = GetPoVTeam()
		units = team and team.units
	end
	local obscured = true
	for _, unit in ipairs(units) do
		obscured = obscured and CheckSightCondition(unit, self, const.usObscured)
	end
	return obscured
end

function Unit:UIConcealed(skip_check)
	local side = self.CurrentSide or (self.team and self.team.side)
	if not side or side == "player1" or side == "player2" or side == "ally" then
		return false
	end
	if not GameState.Fog then
		return false
	end
	if not skip_check and HasThermalVision(Selection) then 
		return false 
	end
	
	local concealed = true
	local units = Selection or empty_table
	if #units == 0 then
		local team = GetPoVTeam()
		units = team and team.units
	end
	for _, unit in ipairs(units) do
		concealed = concealed and CheckSightCondition(unit, self, const.usConcealed)
	end
	return concealed
end

function Unit:GetDisplayName()
	if self:UIObscured() or self:UIConcealed() then
		return T(393866533740, "???")
	end
	
	return UnitProperties.GetDisplayName(self)
end

function Unit:HasVisibleEffects()
	if self.team.neutral then return false end
	return StatusEffectObject.HasVisibleEffects(self)
end

function Unit:FastForwardCommand()
	if self.command == "ExitMap" and not self:HasStatusEffect("DontFastForwardExit") then
		self:Despawn()
	end
end

function Unit:SetCommandIfNotDead(...)
	if self:IsDead() or self.command == "Die" then return end
	self:SetCommand(...)
end

DefineClass.World_HangingSkeleton_Base = {
	__parents = { "CombatObject", "DecorStateFXAutoAttachObject" },
	flags = { efApplyToGrids = false },
}