File size: 69,781 Bytes
b6a38d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
if FirstLoad then
	g_ConflictSectors = false
end

function OnMsg.PreLoadSessionData()
	g_ConflictSectors = {}
	for id, sector in pairs(gv_Sectors) do
		if sector.conflict then
			g_ConflictSectors[#g_ConflictSectors + 1] = id
		end
	end
	table.sort(g_ConflictSectors)
end

function OnMsg.NewGame(game)
	g_ConflictSectors = {}
end

function IsConflictMode(sector_id)
	if sector_id then
		return not not table.find(g_ConflictSectors, sector_id), gv_Sectors[sector_id]
	else
		return #g_ConflictSectors > 0, gv_Sectors[g_ConflictSectors[1]]
	end
end

function AnyNonWaitingConflict()
	for i, sectorId in ipairs(g_ConflictSectors) do
		local sector = gv_Sectors[sectorId]
		if not sector.conflict.waiting then
			return sector
		end
	end
	return false
end

function GetConflictCustomDescr(sector)
	if not sector then return end

	local conflict = sector.conflict
	local preset = conflict and ConflictDescriptionDefs[conflict.descr_id or false]
	local custom = preset and preset.description
	if custom then return custom end
	
	if conflict and conflict.spawn_mode == "defend" then
		return T{129191214872, ConflictDescriptionDefs.DefaultDefend.description, sector} 
	else
		return T{292704915698, ConflictDescriptionDefs.DefaultAttack.description, sector} 
	end
end

function GetConflictCustomTitle(sector)
	if not sector then return end

	local conflict = sector.conflict
	local preset = conflict and ConflictDescriptionDefs[conflict.descr_id or false]
	local custom = preset and preset.title
	if custom then return custom end
	
	return T(829620197199, "ENEMY PRESENCE")
end

TFormat.SectorConflictCustomDescr = GetConflictCustomDescr
TFormat.GetConflictCustomTitle = GetConflictCustomTitle

function SatelliteRetreat(sector_id, sides_to_retreat)
	NetUpdateHash("SatelliteRetreat", sector_id)
	local sector = gv_Sectors[sector_id]
	if not sector.conflict then return end

	sides_to_retreat = sides_to_retreat or {"player1"}
	
	local previousSector = false
	local squadsToRetreat = {}
	for i, squad in ipairs(g_SquadsArray) do
		if squad.militia then goto continue end
		if squad.CurrentSector ~= sector_id then goto continue end
		if not IsSquadInConflict(squad) then goto continue end
		if not table.find(sides_to_retreat, squad.Side) then goto continue end
		
		squadsToRetreat[#squadsToRetreat + 1] = squad
		
		-- How?!?
		if squad.PreviousSector == sector_id then
			squad.PreviousSector = false
		end
		
		if squad.PreviousSector then
			previousSector = squad.PreviousSector
		end
		
		::continue::
	end
	
	-- Make sure all squads have a previous sector (inherit from other squads here)
	-- If none of them have one auto resolve shouldn't have been allowed in the first place.
	-- See IsAutoResolveEnabled
	if previousSector then
		for i, squad in ipairs(squadsToRetreat) do
			if not squad.PreviousSector then
				squad.PreviousSector = previousSector
			end
		end
	end
	
	for i, squad in ipairs(squadsToRetreat) do
		local prev_sector_id = (sector.conflict.player_attacking and sector.conflict.prev_sector_id) or squad.PreviousSector
		if IsWaterSector(prev_sector_id) and squad.PreviousLandSector then
			prev_sector_id = squad.PreviousLandSector
		end
		if not prev_sector_id then goto continue end
		
		if (IsSectorUnderground(sector_id) and not IsSectorUnderground(prev_sector_id)) or
			(IsSectorUnderground(prev_sector_id) and not IsSectorUnderground(sector_id)) then
			SetSatelliteSquadCurrentSector(squad, prev_sector_id, true, true)
		else
			-- Find best retreat sector if previous sector is a bad idea.
			local badRetreat = false
			local otherSideSquads = (squad.Side == "enemy1" or squad.Side == "enemy2") and g_PlayerAndMilitiaSquads or g_EnemySquads
			-- Check if any of the other side squads on my sector are travelling towards the one I want to retreat to.
			for i, os in ipairs(otherSideSquads) do
				if os.CurrentSector == sector_id and os.route then
					local nextDest = os.route[1] and os.route[1][1]
					if nextDest == prev_sector_id then
						badRetreat = true
						break
					end
				end
			end
			
			-- Check if retreating into water.
			local prevSector = gv_Sectors[prev_sector_id]
			local illegalRetreat = prevSector.Passability == "Water" or prevSector.Passability == "Blocked"
			badRetreat = badRetreat or illegalRetreat
			
			-- Check if retreating into enemies.
			if not badRetreat then badRetreat = not not table.find(otherSideSquads, "CurrentSector", prev_sector_id) end
			-- Try to find a better retreat position, such as one without other side squads.
			if badRetreat then
				local illegalRetreatFallback, foundSector = false, false
				ForEachSectorCardinal(sector_id, function(otherSecId)
					local considerThisSector = false
					local otherSec = gv_Sectors[otherSecId]
					if SideIsAlly(otherSec.Side, squad.Side) then -- If my side, then there aren't any baddies there.
						considerThisSector = true
					elseif not table.find(otherSideSquads, "CurrentSector", otherSecId) then
						considerThisSector = true
					end

					local forbiddenRoute = IsRouteForbidden({{otherSecId}}, squad)
				
					-- If illegal retreat consider the first non-forbidden route sector, regardless of the
					-- "other-side" conditions above.
					if illegalRetreat and not illegalRetreatFallback and not forbiddenRoute then
						illegalRetreatFallback = otherSecId
					end

					if considerThisSector and not forbiddenRoute then
						foundSector = true
						prev_sector_id = otherSecId
						return "break"
					end
				end)
				
				if illegalRetreat and not foundSector and illegalRetreatFallback then
					prev_sector_id = illegalRetreatFallback
				end
			end
			
			local retreatRoute = GenerateRouteDijkstra(squad.CurrentSector, prev_sector_id, false, squad.units, "retreat", squad.CurrentSector, squad.side)
			if not retreatRoute then 
				-- Ehh, what?
				assert(false) -- Retreat route is invalid
				retreatRoute = { prev_sector_id } -- Fallback to just get out of this sector.
			end
			
			-- Try to retain the joining squad if it will retreat in the same direction it was going anyway
			local keepJoining = false
			if squad.joining_squad then
				local squadToJoin = gv_Squads[squad.joining_squad]
				keepJoining = squadToJoin and squadToJoin.CurrentSector == prev_sector_id
			end

			SetSatelliteSquadRetreatRoute(squad, { retreatRoute }, keepJoining)
		end
		
		::continue::
	end
	
	ResolveConflict(sector, "no voice", false, "retreat")
	ResumeCampaignTime("UI")
end

function NetSyncEvents.UISatelliteRetreat(sector_id, sides_to_retreat)
	SatelliteRetreat(sector_id, sides_to_retreat)
	local satCon = GetDialog("SatelliteConflict")
	if satCon then CloseDialog("SatelliteConflict") end	
end

GameVar("ForceReloadSectorMap", false)

function EnterConflict(sector, prev_sector_id, spawn_mode, disable_travel, locked, descr_id, force, from_map)
	-- Forced conflicts are resolved via quest events and such,
	sector = sector or gv_Sectors[gv_CurrentSectorId]
	local sector_id = sector and sector.Id
	if not sector then return end
	
	-- Separate enemy attack from player attack to set player_attacking
	local playerInvading = spawn_mode == "attack"
	if spawn_mode == "enemy_attack" then
		spawn_mode = "attack"
	end

	-- Already in conflict, and waiting
	if IsConflictMode(sector_id) then
		if locked ~= nil then sector.conflict.locked = locked end
		if locked ~= nil then sector.conflict.descr_id = descr_id end
		if disable_travel ~= nil then sector.conflict.disable_travel = disable_travel end
		
		--sector.conflict.spawn_mode = spawn_mode or sector.conflict.spawn_mode
		sector.conflict.prev_sector_id = prev_sector_id or sector.conflict.prev_sector_id
		if sector.conflict.waiting then
			sector.conflict.player_attacking = playerInvading
			sector.conflict.waiting = playerInvading or EnemyWantsToWait(sector_id)
			
			if sector.conflict.waiting then
				ResumeCampaignTime("SatelliteConflict")
			else
				PauseCampaignTime("SatelliteConflict")
			end
			
			if gv_SatelliteView then
				ObjModified(SelectedObj)
				ObjModified(Game)
				OpenSatelliteConflictDlg(sector)
				RequestAutosave{ autosave_id = "satelliteConflict", save_state = "CombatStart", display_name = T{285747878633, "Satellite_Conflict_<u(sector)>", sector = sector.name}, mode = "delayed" }
			end
		end
		return
	end
	
	local no_exploration_resolve = false
	if force == "force-exploration-only" then
		no_exploration_resolve = true
	elseif force then
		sector.ForceConflict = true
	end
	table.insert(g_ConflictSectors, sector_id)
	table.sort(g_ConflictSectors)
	sector.conflict = {
		prev_sector_id = prev_sector_id or nil,
		spawn_mode = spawn_mode or nil,
		player_attacking = playerInvading,
		disable_travel = disable_travel or nil,
		locked = locked,
		descr_id = descr_id or sector.CustomConflictDescr or (not playerInvading and "SectorAttacked"),
		waiting = playerInvading or EnemyWantsToWait(sector_id),
		from_map = from_map,
		no_exploration_resolve = no_exploration_resolve
	}
	if InteractionSeeds then
		local prediction, player_power, enemy_power = GetAutoResolveOutcome(sector)
		sector.conflict.predicted_autoresolve = prediction
		sector.conflict.player_power = player_power
		sector.conflict.enemy_power = enemy_power
	end
	
	-- Check if we gameovered in a conflict here then copy special properties.
	if sector.conflict_backup then
		local backupConflict = sector.conflict_backup
		local newConflict = sector.conflict
		
		newConflict.locked = backupConflict.locked
		newConflict.disable_travel = backupConflict.disable_travel
		newConflict.descr_id = backupConflict.descr_id
		newConflict.initial_sector = backupConflict.initial_sector

		sector.conflict_backup = false
	end

	Msg("ConflictStart", sector_id)

	local squads = GetSquadsInSectorCombined(sector_id, false, true)
	for i, squad in ipairs(squads) do
		SatelliteSquadWaitInSector(squad, false)
		if squad.route then squad.route.satellite_tick_passed = false end
		ObjModified(squad)
	end
	
	if gv_SatelliteView then
		OpenSatelliteConflictDlg(sector, "auto-open")
		RequestAutosave{ autosave_id = "satelliteConflict", save_state = "CombatStart", display_name = T{285747878633, "Satellite_Conflict_<u(sector)>", sector = sector.name}, mode = "delayed" }
		if spawn_mode and sector_id == gv_CurrentSectorId then -- if an enemy squad attacks the squad on the current sector, reload sector map
			ForceReloadSectorMap = true
			ObjModified("gv_SatelliteView")
		end
		ObjModified(gv_Squads)
	end

	if not sector.conflict.waiting then PauseCampaignTime("SatelliteConflict") end
	UpdateEntranceAreasVisibility()
	ObjModified(SelectedObj)
	ObjModified(Game)
	
	ExecuteSectorEvents("SE_OnConflictStarted", sector_id)
end

function EnemyWantsToWait(sector, get_squads)
	local enemySquadsEnroute = GetSquadsEnroute(sector, "enemy1")
	if #enemySquadsEnroute == 0 then return false end
	local squads = {}
	local waitTime = const.Satellite.EnemySquadWaitTime
	for i, s in ipairs(enemySquadsEnroute) do
		local estimatedTravelTime = GetTotalRouteTravelTime(s.CurrentSector, s.route, s)
		if estimatedTravelTime < waitTime then
			if not get_squads then
				return true
			else
				squads[#squads+1] = {s, arriving = estimatedTravelTime>0 and estimatedTravelTime or 0}
			end
		end
	end
	if not next(squads) then	
		return false
	else
		return true, squads
	end
end

function CanGoInMap(sector)
	sector = gv_Sectors[sector]
	if not sector.Map then return false end
	if not sector.conflict then return true end
	if not sector.conflict.waiting then return true end

	if sector.conflict.waiting then
		if sector.conflict.player_attacking then
			return true
		end
		return false, "enemy waiting"
	end

	return false
end

local function lTravellingTowardsSectorCenter(sq, sector_id)
	return sq.route and sq.route[1] and #sq.route[1] > 0 and sq.route[1][1] == sector_id
end

-- return value is from player perspective
function GetConflictSide(squad, sector_id)
	local player_squad = squad.Side == "player1" or squad.Side == "player2"
	local owningSide = gv_Sectors[sector_id].Side
	local sectorOwnedByPlayer = owningSide == "player1" or owningSide == "player2" or owningSide == "ally"

	if player_squad and not sectorOwnedByPlayer then
		return "attack"
	elseif not player_squad and not sectorOwnedByPlayer then
		-- the player is attacking, but an enemy reinforcement has arrived
		return "enemy_attack" 
	end

	return "defend"
end

local function lGetSquadsForConflict(squad)
	local sector_id = squad.CurrentSector
	local sector = gv_Sectors[sector_id]
	local allySquads, enemySquads = GetSquadsInSector(sector_id, false, true, true)
	-- note: retreating squads are filtered below conditionally
	
	-- Filter out neutral squads
	local enemiesForReal = {}
	for i, s in ipairs(enemySquads) do
		if s.Side == "enemy1" or s.Side == "enemy2" then
			enemiesForReal[#enemiesForReal + 1] = s
		end
	end
	enemySquads = enemiesForReal
	
	if #allySquads > 0 and #enemySquads > 0 then
		local travellingPlayer = false
		local travellingEnemy = false
		local nonTravellingPlayer = false
		local nonTravellingEnemy = false
		
		local nonRetreatingAlly = {}
		local nonRetreatingEnemy = {}
		for i, squad in ipairs(allySquads) do
			if (not squad.Retreat or SquadReachedDest(squad)) and not IsTraversingShortcut(squad) then
				nonRetreatingAlly[#nonRetreatingAlly + 1] = squad
			end
		end
		for i, squad in ipairs(enemySquads) do
			if (not squad.Retreat or SquadReachedDest(squad)) and not IsTraversingShortcut(squad) then
				nonRetreatingEnemy[#nonRetreatingEnemy + 1] = squad
			end
		end
		
		for i, squad in ipairs(nonRetreatingAlly) do
			local travelling = not IsSquadInSectorVisually(squad, sector_id)
			if travelling then
				travellingPlayer = true
			else
				nonTravellingPlayer = true
			end
		end
	
		for i, squad in ipairs(nonRetreatingEnemy) do
			local travelling = not IsSquadInSectorVisually(squad, sector_id)
			if travelling then
				travellingEnemy = true
			else
				nonTravellingEnemy = true
			end
		end
		
		local bothSidesTraveling = travellingEnemy and travellingPlayer
		local bothSidesInCenter = nonTravellingPlayer and nonTravellingEnemy
		local conflictWillHappen = bothSidesTraveling or bothSidesInCenter
		
		-- If there is an existing conflict (a waiting conflict) retriggering it will end the wait,
		-- however we want that to happen only when a squad reaches the center.
		-- To avoid teleporting squads traveling towards that waiting conflict as soon as
		-- they pass the sector boundary we need the check below.
		--
		-- Note that squads that are past the sector boundary will all get teleported into the conflict
		-- regardless whether the conflict produced will be waiting and they are travelling towards it.
		if sector.conflict then
			conflictWillHappen = conflictWillHappen and IsSquadInSectorVisually(squad, sector_id)
		end
	
		return conflictWillHappen, nonRetreatingAlly, nonRetreatingEnemy
	end
end

function CheckAndEnterConflict(sector, squad, prev_sector_id)
	local sector_id = sector.Id
	
	local conflictSide = GetConflictSide(squad, sector_id)
	if sector.Passability ~= "Water" then
		local conflictStart, playerSquads, enemySquads = lGetSquadsForConflict(squad)
		if conflictStart then
			-- Teleport all travelling squads to the sector center
			for i = 1, #playerSquads + #enemySquads do
				local squad = i <= #playerSquads and playerSquads[i] or enemySquads[i - #playerSquads]
				if IsSquadTravelling(squad) then
					-- Reset travel status to as if plotting a route from conflict.
					squad.route.satellite_tick_passed = false
					
					local movingToConflict = lTravellingTowardsSectorCenter(squad, sector_id)
					SatelliteReachSectorCenter(squad.UniqueId, sector_id, prev_sector_id, not movingToConflict, true)
				end
			end
			EnterConflict(sector, prev_sector_id, conflictSide)
		end
	end
	
	return conflictSide
end

-- Similar code to above but used for SectorEnterConflict effect.
-- The squads returned are the same as the ones returned from PlayerPresentInSector
-- as the two effects are often used together
function ForceEnterConflictEffect(sector, spawnMode, ...)
	local sector_id = sector.Id
	local playerSquads, enemySquads = GetSquadsInSector(sector_id, false, false, true)
	
	-- Dont allow even a forced conflict in this case as it will break the game.
	if #playerSquads == 0 then return end
	
	-- Teleport all travelling squads to the sector center
	for i = 1, #playerSquads + #enemySquads do
		local squad = i <= #playerSquads and playerSquads[i] or enemySquads[i - #playerSquads]
		if IsSquadTravelling(squad) then
			-- Reset travel status to as if plotting a route from conflict.
			squad.route.satellite_tick_passed = false
			
			local movingToConflict = lTravellingTowardsSectorCenter(squad, sector_id)
			SatelliteReachSectorCenter(squad.UniqueId, sector_id, squad.PreviousSector, not movingToConflict, true)
		end
	end
	
	-- Ensure the conflict has a proper spawn mode
	if not spawnMode then
		spawnMode = sector.Side == "player1" and "defend" or "attack"
	end
	
	EnterConflict(sector, nil, spawnMode, ...)
end

function OnMsg.EnterSector(gameStart, gameLoaded)
	if gameLoaded then return end -- Trust the saved ForceReloadSectorMap
	ForceReloadSectorMap = false
end

GameVar("SatQueuedResolveConflict", function() return {} end)

function OnMsg.StartSatelliteGameplay()
	if not SatQueuedResolveConflict or #SatQueuedResolveConflict == 0 then return end
	
	assert(g_SatelliteUI)
	for i, sId in ipairs(SatQueuedResolveConflict) do
		local sector = gv_Sectors[sId]
		if sector.conflict then
			AutoResolveConflict(sector)
		end
	end

	table.clear(SatQueuedResolveConflict)
end

-- bNoVoice is unused
function ResolveConflict(sector, bNoVoice, isAutoResolve, isRetreat)
	gv_ActiveCombat = false
	sector = sector or gv_Sectors[gv_CurrentSectorId]
	
	-- If there is both a militia and enemy squad remaining
	-- autoresolve the conflict between them to decide the outcome.
	local mercSquads, enemySquads = GetSquadsInSector(sector.Id, "no_travel", not "include_militia", "no_arriving", "no_retreat")
	local militiaLeft = GetMilitiaSquads(sector)
	if #militiaLeft > 0 and #enemySquads > 0 then
		if isAutoResolve then
			assert(false) -- Auto resolve is causing another auto resolve, infinite loop!
			table.remove_value(g_ConflictSectors, sector.Id)
			sector.conflict = false
			
			if not AnyNonWaitingConflict() then
				ResumeCampaignTime("SatelliteConflict")	
			end
			return
		end

		if g_SatelliteUI then
			AutoResolveConflict(sector)
		elseif not table.find(SatQueuedResolveConflict, sector.Id) then
			SatQueuedResolveConflict[#SatQueuedResolveConflict + 1] = sector.Id
		end
		return
	end
	
	local playerAttacking = sector.conflict and sector.conflict.player_attacking
	local fromMap = sector.conflict and sector.conflict.from_map

	if sector then -- when going into combat without new game / proper campaign setup
		table.remove_value(g_ConflictSectors, sector.Id)
		sector.conflict = false
		if not g_Combat then
			ShowTacticalNotification("conflictResolved")
			PlayFX("NoEnemiesLeft", "start")
		end
	end
	
	if not AnyNonWaitingConflict() then
		ResumeCampaignTime("SatelliteConflict")	
	end
	UpdateEntranceAreasVisibility()
	
	-- UI update and restoring travel state from before conflict
	local squads = GetSquadsInSector(sector.Id)
	for i, squad in ipairs(squads) do
		ObjModified(squad)
	end
	ObjModified(SelectedObj)
	ObjModified("gv_SatelliteView")

	UpdateSectorControl(sector.Id)
	
	-- Check if player died in tactical view from enemies that dont have squads.
	if (sector.Side == "player1" or sector.Side == "player2") and not gv_SatelliteView and #mercSquads == 0 then
		local playerUnitsOnMap = GetCurrentMapUnits("player")
		local enemyUnitsOnMap = GetCurrentMapUnits("enemy")
		if #playerUnitsOnMap == 0 and #enemyUnitsOnMap > 0 then
			local first = enemyUnitsOnMap[1]
			SatelliteSectorSetSide(sector.Id, "enemy1")
		end
	end

	local playerWon = not isRetreat and (sector.Side == "player1" or sector.Side == "player2")
	if playerWon then
		sector.CustomConflictDescr = false
		RollForMilitiaPromotion(sector)
	end
	
	Msg("ConflictEnd", sector, bNoVoice, playerAttacking, playerWon, isAutoResolve, isRetreat, fromMap)
end

function OnMsg.SquadDespawned(squad_id, sector_id)
	-- Prevent sector takeover on arriving squad despawning on a force conflict sector as
	-- this logic will run before the "squad in sector" logic that will trigger the conflict
	if gv_Sectors[sector_id].ForceConflict then return end
	UpdateSectorControl(sector_id)
end

function UpdateSectorControl(sector_id)
	if not sector_id then
		return
	end
	
	local allySquads, enemySquads = GetSquadsInSector(sector_id, "excludeTravel", "includeMilitia", "excludeArrive", "excludeRetreat")
	local playerHere = #allySquads > 0
	local enemiesHere = false
	for _, squad in ipairs(enemySquads) do
		if squad.Side == "neutral" then goto continue end
	
		local all_dead = true
		for _, unit_id in ipairs(squad.units) do
			local unit = gv_SatelliteView and gv_UnitData[unit_id] or g_Units[unit_id]
			if unit and not unit:IsDead() then
				all_dead = false
				break
			end
		end
		enemiesHere = not all_dead and squad.Side
		
		::continue::
	end

	-- If both sides are present dont update the sector side.
	-- It should be updated by the resolution of the conflict.
	if enemiesHere and playerHere then return end
	
	if enemiesHere then
		SatelliteSectorSetSide(sector_id, enemiesHere)
	elseif playerHere then
		SatelliteSectorSetSide(sector_id, "player1")
	end
end

function NetEvents.ResolveConflict(sector, bNoVoice) -- left only for testing from the console
	ResolveConflict(gv_Sectors[sector], bNoVoice)
end

function GetSectorConflict(sector_id)
	local sector = gv_Sectors and gv_Sectors[sector_id or gv_CurrentSectorId]
	return sector and sector.conflict
end

function SatelliteConflict_IsSquadDefeated(squad)
	local is_squad_defeated = true
	for _, unit_id in ipairs(squad.units) do
		if gv_UnitData[unit_id] and not gv_UnitData[unit_id]:IsDead() then
			is_squad_defeated = false
			break
		end
	end
	return is_squad_defeated
end

function SatelliteConflict_SurviveDefeatedText(squads, lost_text)
	local defeated = 0
	for _, s in ipairs(squads) do
		if SatelliteConflict_IsSquadDefeated(s) then
			defeated = defeated + 1
		end
	end
	local survived = #squads - defeated 	
	local surv = T{221106911816, "<survive> survived", survive = survived==1 and T(792634263677, "1 squad") or T{811215070300, "<count> squads", count = survived}}
	local lost = T{949500986907, "<lost> lost", lost    = defeated==1 and T(792634263677, "1 squad") or T{811215070300, "<count> squads", count = defeated}}
	if lost_text then
		lost = (defeated==1 and T(792634263677, "1 squad") or T{811215070300, "<count> squads", count = defeated}) .." "..lost_text		
	end
	if defeated<=0 then return surv end	
	if survived<=0 then return lost end	
	
	return Untranslated(surv.." / "..lost)
end
function CheckMapConflictResolved(no_voice)
	if GameState.entering_sector then return end

	local sector = gv_Sectors[gv_CurrentSectorId]
	local playerUnits = GetCurrentMapUnits("player")
	local enemy_win = #playerUnits == 0
	local enemy_units = GetCurrentMapUnits("enemy")
	local player_win = true
	for _, unit in ipairs(enemy_units) do
		-- conflict can be resolved if all the remaining enemy units are both non-human and not aware
		player_win = player_win and not unit.Squad and not unit:IsAware()
	end
	if sector and sector.conflict and not sector.conflict.locked and (player_win or enemy_win) then
		sector.ForceConflict = false
		
		local isRetreat = not player_win and enemy_win
		
		-- Assert that this is correct
		if isRetreat then
			for i, u in ipairs(playerUnits) do
				assert(u.retreat_to_sector)
			end
		end
		
		ResolveConflict(sector, no_voice, false, isRetreat)
	end
end

function OnMsg.CombatEnd(combat)
	if not combat.test_combat then
		CheckMapConflictResolved()
	end
end

function OnMsg.UnitDied()
	if not g_Combat then
		CheckMapConflictResolved()
	end
end

function OnMsg.VillainDefeated(unit)
	if not g_Combat then
		CheckMapConflictResolved()
	end
end

function OnMsg.ExplorationTick()
	if g_TestCombat then return end
	
	local sector = gv_Sectors[gv_CurrentSectorId]
	if not sector then return end
	if not sector.conflict then return end
	if sector.conflict.locked then return end
	if sector.conflict.no_exploration_resolve then return end
	if sector.ForceConflict then return end
	
	CheckMapConflictResolved()
end

local function lTacticalModeCheckEnterConflict()
	if GameState.disable_tactical_conflict then return end
	if GameState.Conflict or not gv_ActiveCombat then return end
	
	-- start conflict if there are aware units of opposing sides
	for _, unit in ipairs(g_Units) do
		if not unit:IsAware("pending") then goto continue end
		
		local unitSquad = unit.Squad
		unitSquad = unitSquad and gv_Squads[unitSquad]
		if unitSquad and unitSquad.Retreat then goto continue end
		if unitSquad and unitSquad.CurrentSector ~= gv_CurrentSectorId then goto continue end
		
		local enemies = GetAllEnemyUnits(unit)
		for _, enemy in ipairs(enemies) do
			if not enemy:IsAware("pending") then goto continue end

			local enemySquad = enemy.Squad
			enemySquad = enemySquad and gv_Squads[enemySquad]
			if enemySquad and enemySquad.Retreat then goto continue end
			if enemySquad and enemySquad.CurrentSector ~= gv_CurrentSectorId then goto continue end

			local unitTeam = unit.team
			local enemyTeam = enemy.team
			if unitTeam and enemyTeam then
				local unitTeamSide, enemyTeamSide = unitTeam.side, enemyTeam.side
				local playerPresent = unitTeamSide == "player1" or unitTeamSide == "player2" or enemyTeamSide == "player1" or enemyTeamSide == "player2"
				local enemyPresent = unitTeamSide == "enemy1" or unitTeamSide == "enemy2" or enemyTeamSide == "enemy1" or enemyTeamSide == "enemy2"
				if playerPresent and enemyPresent then
					EnterConflict(nil, nil, nil, nil, nil, nil, nil, "from_map")
				end
			end

			::continue::
		end

		::continue::
	end		
end

OnMsg.CombatStart = lTacticalModeCheckEnterConflict
OnMsg.UnitAwarenessChanged = lTacticalModeCheckEnterConflict

function SatelliteConflictAppliedOnSector(sector)
	return gv_CurrentSectorId == (sector and sector.Id) and CanCloseSatelliteView()
end

-- auto-resolve, autoresolve, auto resolve
GameVar("gv_AutoResolveUseOrdnance", false)

function GetPowerOfUnit(unit, noMods)
	if not unit then return 0 end

	local power
	if IsMerc(unit) then
		power = const.AutoResolve.BaseMercPower * unit:GetLevel()
	elseif unit.Squad and gv_Squads[unit.Squad].militia or unit.militia then
		power = const.AutoResolve.BaseMilitiaPower * unit:GetLevel("baseLevel")
	else -- enemy
		power = const.AutoResolve.BaseEnemyPower * unit:GetLevel("baseLevel")
	end
	
	power = MulDivRound(power, unit:GetProperty("unitPowerModifier"), 100)
	
	if noMods then
		return power
	end
	
	-- in Percents
	local modifier = 100
	-- Health and Wounds mod (power reduced by direct proportion to the units HitPoints/MaxHitPoints)
	local mod = MulDivRound(100, unit.HitPoints or unit.Health, unit:GetInitialMaxHitPoints()) - 100
	modifier = modifier + mod
	
	
	if IsMerc(unit) then
		-- Status Effects mod
		if unit:HasStatusEffect("Tired") then
			modifier = modifier + const.AutoResolve.TiredMod
		end
		
		if unit:HasStatusEffect("Exhausted") then
			modifier = modifier + const.AutoResolve.ExhaustedMod
		end
		
		if unit:HasStatusEffect("WellRested") then
			modifier = modifier + const.AutoResolve.WellRestedMod
		end
		
		-- Armor mod
		modifier = modifier + GetCombinedArmorPowerMod(unit)
		
		-- Weapon mod
		modifier = modifier + GetBestWeaponPowerMod(unit)
		
		-- Ordnance mod
		if gv_AutoResolveUseOrdnance and CanUseOrdnancePower(unit) then
			modifier = modifier + const.AutoResolve.OrdnanceMod
		end
	end
	
	power = MulDivRound(power, modifier, 100)
	return power
end

-- Max mod per Armor piece <maxMod>%. Total 3*<maxMod>%.
-- Based on Direct Proportion of its Cost and <costCap>, also on its condition
function GetCombinedArmorPowerMod(unit)
	local mod = 0
	mod = mod + GetArmorPowerMod(unit:GetItemAtPos("Head", 1, 1))
	mod = mod + GetArmorPowerMod(unit:GetItemAtPos("Torso", 1, 1))
	mod = mod + GetArmorPowerMod(unit:GetItemAtPos("Legs", 1, 1))
	return mod
end

function GetArmorPowerMod(armor)
	if not armor then return 0 end
	
	local maxMod = const.AutoResolve.MaxArmorMod -- Maximum +% mod per Armor piece
	local costCap = const.AutoResolve.MaxArmorModCost
	local mod = Min(maxMod, MulDivRound(maxMod, armor.Cost, costCap))
	mod = MulDivRound(mod, armor.Condition, 100)
	
	return mod
end

-- Max mod <maxMod>% from the best equiped Weapon.
-- Based on Direct Proportion of its Cost and <costCap>, also on its condition
function GetBestWeaponPowerMod(unit)
	local items = unit:GetHandheldItems()
	local mods = {}
	
	for _, item in ipairs(items) do
		mods[#mods+1] = GetWeaponPowerMod(unit, item)
	end
	
	table.sort(mods)
	return mods[#mods] or 0
end

function GetWeaponPowerMod(unit, weapon)
	if not weapon or not IsKindOfClasses(weapon, "Firearm", "MeleeWeapon") then return 0 end
	if IsKindOf(weapon, "MeleeWeapon") and unit.Strength + Unit.Dexterity < const.AutoResolve.MeleeRequiredStats then return 0 end
	if IsKindOf(weapon, "Firearm") and #unit:GetAvailableAmmos(weapon) < 1 then return 0 end -- doesn't have any ammo
	
	local maxMod = const.AutoResolve.MaxWeaponMod -- Maximum +% mod a Weapon can give
	local costCap = const.AutoResolve.MaxWeaponModCost
	local mod = Min(maxMod, MulDivRound(maxMod, weapon.Cost, costCap))
	mod = MulDivRound(mod, weapon.Condition, 100)
	
	return mod
end

-- if has equiped Grenades or Heavy Weapon and Ordnance
function CanUseOrdnancePower(unit)
	local items = unit:GetHandheldItems()
	
	for _, item in ipairs(items) do
		if IsKindOf(item, "Grenade") then
			return true
		elseif IsKindOf(item, "HeavyWeapon") and item.ammo and item.ammo.Amount > 0 then
			return true
		end
	end
	
	return false
end

-- 0% at 50 Leadership, 20% at 100 Leadership
function GetSideLeaderMod(units)
	local mod = 0
	local maxMod = const.AutoResolve.MaxLeaderMod
	local minLeadership = const.AutoResolve.MinLeadershipRequired
	local highestLeadership = 0
	
	for _, unit in ipairs(units) do
		if unit.Leadership > highestLeadership then
			highestLeadership = unit.Leadership
		end
	end
	
	local mod = Max(highestLeadership - minLeadership, 0)
	mod = MulDivRound(maxMod, mod, minLeadership)
	
	return mod
end

function GetSideMedicMod(units)
	local mod = 0
	local minMedical = const.AutoResolve.MinMedicalRequired
	local medics = 0
	
	for _, unit in ipairs(units) do
		if unit.Medical >= minMedical and GetUnitEquippedMedicine(unit) then
			medics = medics + 1
		end
	end
	
	if medics == 0 then
		mod = const.AutoResolve.NoMedicsMod
	elseif medics == 1 then
		mod = 0
	else
		mod = const.AutoResolve.EnoughMedicsMod
	end
	
	return mod
end

function GetSquadPower(squad)
	local power = 0
	if squad.units then
		for _, id in ipairs(squad.units) do
			local unit = gv_UnitData[id]
			power = power + GetPowerOfUnit(unit)
		end
	end
	return power
end

-- Excluding side modifiers
function GetMultipleSquadsPower(squads)
	local power = 0
	for _, squad in ipairs(squads) do
		power = power + GetSquadPower(squad)
	end
	return power
end

-- Including side modifiers
function GetSectorPowersInConflict(sector, playerSquads, enemySquads, disableRandomMod)
	-- Combined power of individual units
	if not playerSquads or not enemySquads then
		local playerSquads, enemySquads = GetSquadsInSector(sector.Id, "excludeTravelling", "includeMilitia", "excludeArriving")
	end
	local playerPower = GetMultipleSquadsPower(playerSquads)
	local enemyPower = GetMultipleSquadsPower(enemySquads)
	
	local playerUnits = GetUnitsFromSquads(playerSquads, "getUnitData")
	local enemyUnits = GetUnitsFromSquads(enemySquads, "getUnitData")
	
	local playerMod = 100 -- percent
	local enemyMod = 100

	local militiaOnlyTeam = true
	for _, unit in ipairs(playerUnits) do
		if IsMerc(unit) then
			militiaOnlyTeam = false
			break
		end
	end
	
	if not militiaOnlyTeam then
		-- Leader mod 
		playerMod = playerMod + GetSideLeaderMod(playerUnits)
		
		-- Medic mod
		playerMod = playerMod + GetSideMedicMod(playerUnits)
		
		-- Numerical Advantage mod
		if #playerUnits >= #enemyUnits * 2 then
			playerMod = playerMod + const.AutoResolve.NumericalAdvantageMod
		elseif #enemyUnits >= #playerUnits * 2 then
			playerMod = playerMod - const.AutoResolve.NumericalAdvantageMod
		end
	end
	
	-- Randomization mod: -<value>% to +<value>% (Applied to attacker)
	if sector.conflict and not disableRandomMod then
		local attackerMod = const.AutoResolve.AttackerRandomMod
		attackerMod = InteractionRandRange(-attackerMod, attackerMod, "AutoResolve")
		if sector.conflict.spawn_mode == "attack" then -- player is attacker
			playerMod = playerMod + attackerMod
		else
			enemyMod = enemyMod + attackerMod
		end
	end
	
	playerPower = MulDivRound(playerPower, playerMod, 100)
	enemyPower = MulDivRound(enemyPower, enemyMod, 100)
	
	-- Deffender bonus
	if sector.conflict then
		local bonus = sector.AutoResolveDefenderBonus
		if sector.conflict.spawn_mode == "attack" then -- player is attacker
			playerPower = playerPower + bonus
		else
			enemyPower = enemyPower + bonus
		end
	end
	
	return playerPower, enemyPower, playerMod
end

function GetAutoResolveOutcome(sector, disableRandomMod)
	local playerSquads, enemySquads = GetSquadsInSector(sector.Id, "excludeTravelling", "includeMilitia", "excludeArriving", "excludeRetreat")
	local playerPower, enemyPower, playerMod = GetSectorPowersInConflict(sector, playerSquads, enemySquads, disableRandomMod)
	
	-- Decide Outcome
	if CheatEnabled("AutoResolve") then
		return "decisive_win", playerPower, enemyPower, playerMod
	end
	
	if playerPower > 2*enemyPower then
		return "decisive_win", playerPower, enemyPower, playerMod
	elseif playerPower >= enemyPower then
		return "win", playerPower, enemyPower, playerMod
	elseif enemyPower > 2*playerPower then
		return "crushing_defeat", playerPower, enemyPower, playerMod
	else
		return "defeat", playerPower, enemyPower, playerMod
	end
end

MapVar("g_AccumulatedTeamXP", false)

function LogAccumulatedTeamXP(actor)
	if g_AccumulatedTeamXP then
		local log_msg
		for _, unit in ipairs(table.keys(g_AccumulatedTeamXP, "sorted")) do
			log_msg = log_msg or { T(280141508210, "Gained XP:") }
			log_msg[#log_msg + 1] = T{547096297080, " <unit>(<em><gain></em>)", unit = unit, gain = g_AccumulatedTeamXP[unit] }
		end
		
		if next(log_msg) then CombatLog(actor, table.concat(log_msg)) end
	end
	g_AccumulatedTeamXP = false
end

function CalculateAutoResolveUnitDamage(unit, outcome, side)
	local injuryChances = {
		decisive_win = { seriousInjury = const.AutoResolveDamage.DecisiveWinSeriousInjuryChance, injury = const.AutoResolveDamage.DecisiveWinInjuryChance }, -- 5% Serious Injury chance, 30% Injury chance
		win = { seriousInjury = const.AutoResolveDamage.WinSeriousInjuryChance, injury = const.AutoResolveDamage.WinInjuryChance }, -- 15% Serious Injury chance, 50% Injury chance
		defeat = { seriousInjury = const.AutoResolveDamage.DefeatSeriousInjuryChance, injury = const.AutoResolveDamage.DefeatInjuryChance }, -- 10% Serious Injury chance, 90% Injury chance
		crushing_defeat = { seriousInjury = const.AutoResolveDamage.CrushingDefeatSeriousInjuryChance, injury = const.AutoResolveDamage.CrushingDefeatInjuryChance}, -- 50% Serious Injury chance, 50% Injury chance
	}
	
	local militiaInjuryChanceMod = 0
	--adjust base and random dmg values and chances based on difficulty
	if side == "enemy" then
		local bonus = (GameDifficulties[Game.game_difficulty]:ResolveValue("autoResolveInjuryChanceEnemyBonus") or 0)
		injuryChances.decisive_win.injury = injuryChances.decisive_win.injury + bonus
		injuryChances.win.seriousInjury = injuryChances.win.seriousInjury + bonus
		injuryChances.win.injury = injuryChances.win.injury + bonus
		injuryChances.defeat.seriousInjury = injuryChances.defeat.seriousInjury + bonus
		injuryChances.crushing_defeat.seriousInjury = injuryChances.crushing_defeat.seriousInjury + bonus
	elseif side == "militia" then
		militiaInjuryChanceMod = const.AutoResolveDamage.MilitiaInjuryAdditiveMod
	end

	local percChangePerDiff = 100
	if side == "enemy" then
		--percChangePerDiff = PercentModifyByDifficulty(GameDifficulties[Game.game_difficulty]:ResolveValue("autoResolveEnemyDmgBonus"))
	elseif side == "player" then
		--percChangePerDiff = PercentModifyByDifficulty(GameDifficulties[Game.game_difficulty]:ResolveValue("autoResolvePlayerDmgBonus"))
	end
	
	local injuryDamage = MulDivRound(const.AutoResolveDamage.InjuryBaseDamage, percChangePerDiff, 100)
	local injuryRandomDamage = MulDivRound(const.AutoResolveDamage.InjuryRandomDamage, percChangePerDiff, 100)
	local seriousInjuryDamage = MulDivRound(const.AutoResolveDamage.SeriousInjuryBaseDamage, percChangePerDiff, 100)
	local seriousInjuryRandomDamage = MulDivRound(const.AutoResolveDamage.SeriousInjuryRandomDamage, percChangePerDiff, 100) -- applies 2 times
	
	local damage = 0
	local injury = false
	
	local injuryRoll = InteractionRand(100, "DamageOnAutoResolve") + 1
	if injuryRoll <= (injuryChances[outcome].seriousInjury + militiaInjuryChanceMod) then -- Unit got SeriouslyInjured
		damage = seriousInjuryDamage + InteractionRand(seriousInjuryRandomDamage, "DamageOnAutoResolve") + InteractionRand(seriousInjuryRandomDamage, "DamageOnAutoResolve")
		injury = "seriousInjury"
	elseif injuryRoll <= (injuryChances[outcome].injury + militiaInjuryChanceMod) then -- Unit got Injured
		damage = injuryDamage + InteractionRand(injuryRandomDamage, "DamageOnAutoResolve")
		injury = "injury"
	end
	
	return damage, injury
end

function AutoResolveUseMeds(playerSquads)
	local bestMedic = false
	local medkit = false
	
	for _, squad in ipairs(playerSquads) do
		for _, id in ipairs(squad.units) do
			local unit = gv_UnitData[id]
			local umedkit = GetUnitEquippedMedicine(unit)
			if umedkit and (not bestMedic or bestMedic.Medical < unit.Medical) then
				bestMedic = unit
				medkit = umedkit
			end
		end
	end
	
	if bestMedic then		
		for _, squad in ipairs(playerSquads) do
			for _, id in ipairs(squad.units) do
				local unit = gv_UnitData[id]				
				unit:GetBandaged(medkit, bestMedic)
			end
		end
	end
end

function AutoResolveUseAmmo(playerSquads, damageDone)
	local damageToUseAmmo = const.AutoResolveResources.DamageToAmmo
	local playerUnitsCount = CountUnitsInSquads(playerSquads)
	local baseAmmoUsagePerUnit = DivRound(damageDone, damageToUseAmmo * playerUnitsCount)
	
	local function TakeItemAmount(item, amount, container, slot)
		local used = Min(item.Amount, amount)
		item.Amount = item.Amount - used
		if item.Amount <= 0 then
			if slot then
				container:RemoveItem(slot, item, "no_update")
			elseif container then --presumably, squad bag which is an array..
				table.remove_entry(container, item)
			end
			DoneObject(item)
		end
		return used
	end
	
	for _, squad in ipairs(playerSquads) do
		for _, id in ipairs(squad.units) do
			local unit = gv_UnitData[id]
	
			local ammoRandMult = InteractionRand(50, "AutoResolveAmmo")
			local ammoToUse = MulDivRound(baseAmmoUsagePerUnit, 100 + ammoRandMult, 100)
			local handeldItems, handeldItemsSlots = unit:GetHandheldItems()
			
			if gv_AutoResolveUseOrdnance then
				local allowedOrdnance = 1 + InteractionRand(const.AutoResolveResources.MaxOrdnanceUsed, "AutoResolveAmmo")
				local ordnanceToAmmoMult = 3
				for i, item in ipairs(handeldItems) do
					if ammoToUse <= 0 or allowedOrdnance <= 0 then break end
					
					if IsKindOf(item, "Grenade") then
						local used = TakeItemAmount(item, allowedOrdnance, unit, handeldItemsSlots[i])
						allowedOrdnance = allowedOrdnance - used
						ammoToUse = ammoToUse - used * ordnanceToAmmoMult
					elseif IsKindOf(item, "HeavyWeapon") then
						local degrade = -item:GetBaseDegradePerShot()
						local ammos, containers, slots = unit:GetAvailableAmmos(item)
						for j, ammo in ipairs(ammos) do -- Use from AmmoPack and UnitInventory
							local used = TakeItemAmount(ammo, allowedOrdnance, containers[j], slots[j])
							allowedOrdnance = allowedOrdnance - used
							ammoToUse = ammoToUse - used * ordnanceToAmmoMult
							unit:ItemModifyCondition(item, degrade * used)
						end
						
						if allowedOrdnance > 0 and ammoToUse > 0 and item.ammo then -- Use from Weapon itself
							local used = TakeItemAmount(item.ammo, allowedOrdnance)
							allowedOrdnance = allowedOrdnance - used
							ammoToUse = ammoToUse - used * ordnanceToAmmoMult
							unit:ItemModifyCondition(item, degrade * used)
						end
					end
				end
			end
			
			for _, item in ipairs(handeldItems) do
				if ammoToUse <= 0 then break end
				
				if IsKindOf(item, "Firearm") then
					local degrade = -item:GetBaseDegradePerShot()
					local ammos, containers, slots = unit:GetAvailableAmmos(item)
					for j, ammo in ipairs(ammos) do -- Use from AmmoPack and UnitInventory
						local used = TakeItemAmount(ammo, ammoToUse, containers[j], slots[j])
						ammoToUse = ammoToUse - used
						unit:ItemModifyCondition(item, degrade * used)
					end
					
					if ammoToUse > 0 and item.ammo then -- Use from Weapon itself
						local used = TakeItemAmount(item.ammo, ammoToUse)
						ammoToUse = ammoToUse - used
						unit:ItemModifyCondition(item, degrade * used)
					end
				end
			end
		end
	end
end

function AutoResolveArmorDegradation(unit, injury)
	if not unit or not injury then return end
	
	local armorPieces = {}
	armorPieces[#armorPieces+1] = unit:GetItemAtPos("Head", 1, 1)
	armorPieces[#armorPieces+1] = unit:GetItemAtPos("Torso", 1, 1)
	armorPieces[#armorPieces+1] = unit:GetItemAtPos("Legs", 1, 1)
	
	local times = injury == "seriousInjury" and const.AutoResolveResources.ArmorDegradationTimesSeriousInjury or const.AutoResolveResources.ArmorDegradationTimesInjury
	
	for i = 1, times do
		if #armorPieces == 0 then return end

		local idx = InteractionRand(#armorPieces, "AutoResolveArmor") + 1
		local item = armorPieces[idx]
		
		unit:ItemModifyCondition(item, -item.Degradation)
		
		if item.Condition <= 0 then
			table.remove(armorPieces, idx)
		end
	end
end

function ApplyAutoResolveOutcome(sector, playerOutcome)
	local playerWins = IsOutcomeWin(playerOutcome)
	local enemyOutcome = GetOppositeOutcome(playerOutcome)
	local playerSquads, enemySquads = GetSquadsInSector(sector.Id, "excludeTravelling", not "includeMilitia", "excludeArriving", "excludeRetreating")
	local items = {}
	
	-- Militia outcome
	local militiaSquads = GetMilitiaSquads(sector)
	local militiaUnitsCount = CountUnitsInSquads(militiaSquads)
	local militiaKilled = 0
	for i = #militiaSquads, 1, -1 do
		local squad = militiaSquads[i]
		for j = #squad.units, 1, -1 do
			local id = squad.units[j]
			local unit = gv_UnitData[id]
			local damage = 0
			
			-- When the unit appears twice in a squad (due to another bug), this will error.
			if not unit then goto continue end
			
			if not playerWins then -- all militia die if the player loses;
				damage = unit.HitPoints
			else
				local deathRoll = InteractionRand(100, "AutoResolve")
				local deathChance = playerOutcome == "decisive_win" and const.AutoResolveDamage.NPCDeathChanceOnDecisiveWin or const.AutoResolveDamage.NPCDeathChanceOnWin
				if deathRoll < deathChance then
					damage = unit.HitPoints
				else
					damage = CalculateAutoResolveUnitDamage(unit, playerOutcome, "militia")
					local militiaDamageMultiplier = const.AutoResolveDamage.MilitiaDamageTakenMod -- percent
					damage = MulDivRound(damage, 100 + militiaDamageMultiplier, 100)
				end
			end
			
			unit.HitPoints = Max(unit.HitPoints - damage, 0)
			unit:AccumulateDamageTaken(damage)
			
			if playerWins and #playerSquads <= 0 and (militiaKilled == militiaUnitsCount - 1) then -- let the last militia survive when defending with no mercs
				unit.HitPoints = 1
			end
			
			if unit.HitPoints <= 0 then
				militiaKilled = militiaKilled + 1
				unit:Die()
				Unit.DropLoot(unit)
				if playerWins then
					unit:ForEachItem(function(item, slot_name, left, top, items)
						items[#items + 1] = item
						unit:RemoveItem(slot_name, item)
					end, items)
				end
			end
			
			::continue::
		end
	end
	
	-- Enemies outcome
	g_AccumulatedTeamXP = {}
	local totalDamageToEnemy = 0
	for i = #enemySquads, 1, -1 do
		for j = #enemySquads[i].units, 1, -1 do
			local id = enemySquads[i].units[j]
			local unit = gv_UnitData[id]
			local damage = 0
			
			if playerWins then -- all enemies die if the player wins;
				damage = unit.HitPoints
			else
				local deathRoll = InteractionRand(100, "AutoResolve")
				local deathChance = enemyOutcome == "decisive_win" and const.AutoResolveDamage.NPCDeathChanceOnDecisiveWin or const.AutoResolveDamage.NPCDeathChanceOnWin
				if deathRoll < deathChance then
					damage = unit.HitPoints
				else
					damage = CalculateAutoResolveUnitDamage(unit, enemyOutcome, "enemy")
				end
			end
			
			unit.HitPoints = Max(unit.HitPoints - damage, 0)
			--unit:AccumulateDamageTaken(damage)
			
			if unit.villain and not playerWins then -- don't kill the villain
				unit.HitPoints = 1
			end
		
			if unit.HitPoints <= 0 then
				unit:Die()
			end
			
			totalDamageToEnemy = totalDamageToEnemy + damage
			
			if playerWins then -- Generate loot
				Unit.DropLoot(unit)
				unit:ForEachItem(function(item, slot_name, left, top, items)
					items[#items + 1] = item
					unit:RemoveItem(slot_name, item)
				end, items)
			end
		end
	end
	
	-- Player outcome
	-- Consume Resources
	if #playerSquads > 0 then -- Militia only autoresolve
		AutoResolveUseAmmo(playerSquads, totalDamageToEnemy)
	end
	
	-- Damage Units
	local playerUnitsCount = CountUnitsInSquads(playerSquads)
	local mercsKilled = 0
	for i = #playerSquads, 1, -1 do
		local squad = playerSquads[i]
		for j = #squad.units, 1, -1 do
			local id = squad.units[j]
			local unit = gv_UnitData[id]
			local damage = 0
			local injury
			
			damage, injury = CalculateAutoResolveUnitDamage(unit, playerOutcome, "player")
			
			if injury then
				AutoResolveArmorDegradation(unit, injury)
			end
			
			if injury == "seriousInjury" and unit.Tiredness < 1 then
				unit:SetTired(unit.Tiredness + 1)
			end
			
			unit.HitPoints = Max(unit.HitPoints - damage, 0)
			unit:AccumulateDamageTaken(damage)
			
			if playerWins and (mercsKilled == playerUnitsCount - 1) then -- let the last Merc survive
				unit.HitPoints = 1
			end
			
			if unit.HitPoints <= 0 then
				mercsKilled = mercsKilled + 1
				unit:Die()
			end
		end
	end
	--AutoResolveUseMeds(playerSquads)
	
	if #items > 0 then
		SortItemsArray(items)
	end
	LogAccumulatedTeamXP("short")
	
	return items
end

function IsOutcomeWin(outcome)
	return outcome == "decisive_win" or outcome == "win"
end

function GetOppositeOutcome(outcome)
	if outcome == "decisive_win" then return "crushing_defeat" end
	if outcome == "win" then return "defeat" end
	if outcome == "defeat" then return "win" end
	if outcome == "crushing_defeat" then return "decisive_win" end
end

function NetEvents.CloseOtherGuysAutoResolveResultsUI()
	local dlg = GetDialog("SatelliteConflict")
	if dlg then
		dlg:Close()
	end
end

local function RecalcNames(sector, oldAllySquads)
	for _, squad in ipairs(oldAllySquads) do
		local squadUnits = table.copy(squad.units)
		for id, unitId in ipairs(squadUnits) do
			if not gv_UnitData[unitId] then
				table.remove(squad.units, table.find(squad.units, unitId))
			end
		end
	end
	local allySquads = GetGroupedSquads(sector.Id, true, false, "no_retreating")
	
	for i, s in ipairs(allySquads) do
		for i, u in ipairs(s.units) do
			local unitData = gv_UnitData[u]
			local squad = table.find_value(oldAllySquads, "UniqueId", s.UniqueId)
			if squad and not table.find(squad.units, unitData.session_id) then
				table.insert(squad.units, unitData.session_id)
			end
		end
	end
	
	return oldAllySquads
end

function lCopySquadsBeforeAutoResolve(squadList)
	local newList = {}
	for i, s in ipairs(squadList) do
		local copy = {
			units = table.copy(s.units),
			Name = s.Name,
			CurrentSector = s.CurrentSector,
			UniqueId = s.UniqueId,
			image = s.image,
			Retreat = s.Retreat,
			militia = s.militia
		}
		newList[#newList + 1] = copy
	end
	return newList
end

function AutoResolveConflict(sector)
	local player_outcome = GetAutoResolveOutcome(sector)
	local player_wins = IsOutcomeWin(player_outcome)
	
	--save the needed data for the auto-resolve screen
	--todo: maybe GetAutoResolveOutcome should return squads
	local allySquads = GetGroupedSquads(sector.Id, "includeMilitia", not "get_enemies", "no_retreating", "exclude_travelling")
	local enemySquads = GetGroupedSquads(sector.Id, not "includeMilitia", "get_enemies", "no_retreating", "exclude_travelling")
	enemySquads = enemySquads or {}
	
	-- Auto resolve will cause units to be ejected from the squads,
	-- so we need to copy the data.
	allySquads = lCopySquadsBeforeAutoResolve(allySquads)
	enemySquads = lCopySquadsBeforeAutoResolve(enemySquads)
	
	local loot = ApplyAutoResolveOutcome(sector, player_outcome)

	-- Sync to prevent ongoing combat hang if retreat->autoresolve due to militia
	if sector.Id == gv_CurrentSectorId and not ForceReloadSectorMap then
		LocalCheckUnitsMapPresence()
		SyncUnitProperties("session")
	end

	-- todo: can this reuse the information from above once it is refactored to get it from GetOutcome?
	local playerSquads = GetSquadsInSector(sector.Id, "excludeTravelling", not "includeMilitia", "excludeArriving", "excludeRetreating")
	local first_alive_merc
	for _, squad in ipairs(playerSquads) do
		for _, id in ipairs(squad.units) do
			local unit = gv_UnitData[id]
			if unit.Squad and unit.HireStatus ~= "Dead" then
				first_alive_merc = unit
				break
			end
		end
		if first_alive_merc then
			break
		end
	end
	
	local playerPower, enemyPower, playerMod = GetSectorPowersInConflict(sector, allySquads, enemySquads, "disableRandomMod")
	allySquads.power = playerPower
	allySquads.playerMod = playerMod
	enemySquads.power = enemyPower
	
	local items = table.copy(loot)
	local sectorStash = GetSectorInventory(sector.Id)
	assert(sectorStash)
	if sectorStash then
		AddItemsToInventory(sectorStash, items)
	end
	
	PauseCampaignTime("SatelliteConflictOutcome")
	
	if player_wins then
		sector.ForceConflict = false
		ResolveConflict(sector, nil, "auto-resolve", nil)
	elseif first_alive_merc then -- retreat mercs
		SatelliteRetreat(sector.Id)
	else -- no mercs left alive
		ResolveConflict(sector, "no voice", "auto-resolve", nil)
		ResumeCampaignTime("UI")
	end

	-- recalc squads to handle promoted militia
	allySquads = RecalcNames(sector, allySquads)
	
	OpenSatelliteConflictDlg(
		{
			player_outcome = player_outcome,
			allySquads = allySquads,
			enemySquads = enemySquads,
			sector = sector,
			loot = loot,
			first_alive_merc = first_alive_merc,
			autoResolve = true
		})
	ResumeCampaignTime("SatelliteConflictOutcome")
	
	ObjModified("sector_selection_changed")
	ObjModified("sector_selection_changed_actions")
	Msg("AutoResolvedConflict", sector.Id, player_outcome)
end

function NetSyncEvents.UIAutoResolveConflict(sector_id, ordenance)
	local sector = gv_Sectors[sector_id]
	if not sector.conflict then return end
	local old = gv_AutoResolveUseOrdnance
	gv_AutoResolveUseOrdnance = ordenance --quick and dirty fix for autoresolve using ui button state, this will only work if there is no sleeps/threads n such
	AutoResolveConflict(sector)
	gv_AutoResolveUseOrdnance = old
	local dlg = GetDialog("SatelliteConflict")
	if dlg then
		dlg:Close()
	end
end

function TFormat.AutoResolveOutcomeText(context_obj, status)
	if status == "decisive_win" then
		return T(907277131281, "DECISIVE WIN")
	elseif status == "win" then
		return T(561227589007, "VICTORY")
	elseif status == "defeat" then
		return T(979864159307, "DEFEAT")
	elseif status == "crushing_defeat" then
		return T(912438837574, "CRUSHING DEFEAT")
	end
end

function RollForMilitiaPromotion(sector)
	local squads = GetMilitiaSquads(sector)
	local promotedCount = 0
	
	for _, squad in ipairs(squads) do
		local unitIds = table.copy(squad.units)
		
		for _, id in ipairs(unitIds) do
			--local unit = g_Units[id]
			local unitData = gv_UnitData[id]
			
			local chance = 30
			local roll = InteractionRand(100, "MilitiaPromotion")
			
			if roll < chance then
				if unitData.class == "MilitiaRookie" then
					CreateMilitiaUnitData("MilitiaVeteran", sector, squad)
					DeleteMilitiaUnitData(unitData.session_id, squad)
					
					promotedCount = promotedCount + 1
				elseif unitData.class == "MilitiaVeteran" then
					CreateMilitiaUnitData("MilitiaElite", sector, squad)
					DeleteMilitiaUnitData(unitData.session_id, squad)
					
					promotedCount = promotedCount + 1
				end
			end
		end
	end
	
	if promotedCount > 0 then
		if promotedCount > 1 then
			CombatLog("important", T{293615811082, "<promotedCount> militia got promoted in <SectorName(sectorId)>", promotedCount = promotedCount, sectorId = sector.Id})
		else
			CombatLog("important", T{488327770041, "A militia unit got promoted in <SectorName(sectorId)>", promotedCount = promotedCount, sectorId = sector.Id})
		end
	end
end

-- remove enemy units/squads from a sector
-- value is an signed number, denoting whether and how many units to add or remove
-- valueType is a string, can either "count" which means value is a specific count or "percent"
function ModifySectorEnemySquads(sector_id, value, valueType, class)
	if value == 0 then
		return
	end
	valueType = valueType or "percent"
	
	local squads = {}
	local mercs, mercsPerSquad = {}, {}
	local enemySquads = GetSectorSquadsFromSide(sector_id, "enemy1", "enemy2")
	for i, squad in ipairs(enemySquads) do
		if not squad.villain and not squad.guardpost then
			for _, merc in ipairs(squad.units) do
				local unit = gv_UnitData[merc]
				if (not class and not unit.villain and not HasAnyShipmentItem(unit)) or unit.class == class then
					mercs[#mercs+1] = merc
					if not mercsPerSquad[squad] then mercsPerSquad[squad] = {} end
					mercsPerSquad[squad][#mercsPerSquad + 1] = merc
				end	
			end
			if EnemySquadDefs[squad.enemy_squad_def] then
				squads[#squads + 1] = squad
			end
		end
	end
	
	if value < 0 then -- Remove units
		value = abs(value)
		local removeAll = (valueType == "percent" and value == 100) or (valueType == "count" and value == #mercs)
		if removeAll then
			for _, merc in ipairs(mercs) do
				RemoveUnitFromSquad(gv_UnitData[merc], "despawn")
			end
		else
			local count = valueType == "count" and value or MulDivRound(value, #mercs, 100)
			count = Max(count, 1)
			for i = 1, Min(count, #mercs) do
				local merc, idx = table.interaction_rand(mercs, "SectorEnemySquads")
				table.remove(mercs, idx)
				RemoveUnitFromSquad(gv_UnitData[merc], "despawn")
			end
		end
	else -- Add units
		for _, squad in ipairs(squads) do
			-- Note: If the value is a percent it is relative to the current number of units of the same type in the sector.
			local count = valueType == "count" and value or MulDivRound(value, #mercsPerSquad[squad], 100)
			count = Max(count, 1)
			
			local units_to_create = {}
			if class then
				for i = 1, count do
					units_to_create[i] = class
				end
			else			
				while count > 0 do
					local unit_template_ids = GenerateRandEnemySquadUnits(squad.enemy_squad_def)
					if #unit_template_ids == 0 then
						assert(false, "We risk infinite loop here, something is wrong with the enemy squad definition. Not all enemy units will be created from this ModifySectorEnemySquads effect.")
						break
					end
					local all = #unit_template_ids
					for i = 1, all do
						local id, idx = table.interaction_rand(unit_template_ids, "SectorEnemySquads")
						units_to_create[#units_to_create + 1] = id
						table.remove(unit_template_ids, idx)
						count = count - 1
						if count == 0 then
							break
						end
					end
				end	
			end

			local new_units = GenerateUnitsFromTemplates(squad.CurrentSector, units_to_create, "ModifyEffect")
			AddUnitsToSquad(squad, new_units)
		end
	end
	
	if not gv_SatelliteView and sector_id == gv_CurrentSectorId then
		LocalCheckUnitsMapPresence()
	end
end

DefineClass.SatelliteConflictUIMercsDisplay = {
	__parents = { "XContextWindow" },
	GridWidth = 2,
	LayoutMethod = "Vlist",
	LayoutVSpacing = 10,
	MinHeight = 330,
	MaxHeight = 450,
	
	properties = {
		{ category = "MercDisplay", id = "headerText", name = "Header Name", editor = "text", default = "", translate = true },
		{ category = "MercDisplay", id = "subheaderText", name = "Subheader", editor = "text", default = "", translate = true },
		{ category = "MercDisplay", id = "showEnroute", name = "ShowEnroute", editor = "bool", default = "" },
		{ category = "MercDisplay", id = "align", name = "Align", editor = "choice", items = { "left", "right" }, default = "left" },
	}
}

function SatelliteConflictUIMercsDisplay:Open()
	self.idHeaderTitle:SetText(self.headerText)
	self.idSubHeaderText:SetText(self.subheaderText)
	XContextWindow.Open(self)
	
	if self.align == "right" then
		self.idHeader:SetHAlign("left")
		self.idHeaderTitle:SetHAlign("left")
		self.idHeaderLine:SetHAlign("left")
		self.idSubHeader:SetHAlign("left")
		
		local margins = self.idHeader.Margins
		self.idHeader:SetMargins(box(margins:maxx(), margins:miny(), margins:minx(), margins:maxy()))
	
		local paddings = self.idMercs.Padding
		self.idMercs:SetPadding(box(paddings:maxx(), paddings:miny(), paddings:minx(), paddings:maxy()))
		
		for i, s in ipairs(self.idMercs) do
			s:SetHAlign("left")
			if rawget(s, "idMercContainer") then
				s.idMercContainer:SetHAlign("left")
			end
			s:SetMargins(box(20, 0, 0, 0))
		end
	end
end

function SatelliteConflictUIMercsDisplay:GetMercUnitData(context)
	if context.UniqueId then
		return GetMercArrayUnitData(context.units) or {}
	else
		if not context.units or #context.units == 0 then
			return false
		end
		return table.imap(context.units, function(o)
			local propObj = ResolvePropObj(o) or o
			if IsKindOf(propObj, "UnitData") then return o end
			return SubContext(o.template, o)
		end)
	end
end

function SatelliteConflictUIMercsDisplay:SplitMercsIntoSquads(context)
	if not context.units then return {context} end
	
	local maxPeopleInSquad = const.Satellite.MercSquadMaxPeople
	local squadCount = #context.units > maxPeopleInSquad and MulDivRound(#context.units, 1000, maxPeopleInSquad * 1000) or 1
	local squads = {}
	for i = 0, squadCount - 1 do
		local units = {}
		local startIdx = (maxPeopleInSquad * i) + 1
		for m = startIdx, Min(startIdx + maxPeopleInSquad - 1, #context.units) do
			units[#units + 1] = context.units[m]
		end
		squads[i + 1] = {
			units = units
		}
	end
	return squads
end

GameVar("LostLoyaltyWithSectorsThisTick", false) -- Used to prevent double penalties

function OnMsg.SatelliteTick()
	LostLoyaltyWithSectorsThisTick = false
end

function GetLoyaltyCityNearby(sector, filter)
	if filter == "center_only" then
		local s = gv_Sectors[sector.Id]
		local city = s and s.City
		if city and city ~= "none" then
			return city
		else
			return
		end
	end
	
	local city = gv_Sectors[sector.Id].City
	if not filter and city and city ~= "none" then
		return city
	end
	
	city = nil
	ForEachSectorAround(sector.Id, 1, function(sector_id)
		if filter == "adjacent_only" and sector_id == sector.Id then return end
	
		-- If any of the adjacent sectors is part of a city
		local s = gv_Sectors[sector_id]
		if s and s.City and s.City ~= "none" then
			city = s.City
			return "break"
		end
	end)
	return city
end

function OnMsg.SectorSideChanged(sector_id, oldSide, newSide)
	-- Lost control of a sector that belongs to a city
	if oldSide == "player1" and newSide == "enemy1" then
		if LostLoyaltyWithSectorsThisTick and LostLoyaltyWithSectorsThisTick[sector_id] then return end
	
		local sector = gv_Sectors[sector_id]
		if sector.conflict then return end -- Conflict End will handle loyalty change
		
		local city = GetLoyaltyCityNearby(sector, "center_only")
		CityModifyLoyalty(city, const.Loyalty.CitySectorEnemyTakeOverLoyaltyLoss, T(171133072609, "City Lost"))
	end
end

function CivilianDeathPenalty()
	local penaltyAmount = const.Loyalty.CivilianDeathPenalty
	local penaltyCap = const.Loyalty.CivilianDeathPenaltyCityCap
	local currentSector = gv_Sectors[gv_CurrentSectorId]
	local cityId = currentSector and GetLoyaltyCityNearby(currentSector)
	local city = gv_Cities[cityId]
	if not city then return end
	
	if city.currentCivilianDeathPenalty + penaltyAmount > penaltyCap then penaltyAmount = penaltyCap - city.currentCivilianDeathPenalty end
	if city.Loyalty - penaltyAmount < 0 then penaltyAmount = city.Loyalty end
	local oldLoyalty = city.Loyalty
	CityModifyLoyalty(cityId, -penaltyAmount, T(938505306538, "Civilian death penalty"))
	if oldLoyalty > city.Loyalty then
		city.currentCivilianDeathPenalty = city.currentCivilianDeathPenalty + penaltyAmount
	end
end

function OnMsg.SectorSideChanged(sector_id, oldSide, newSide)
	-- reset conflictLoyaltyGained
	if oldSide == "player1" and newSide == "enemy1" then
		local sector = gv_Sectors[sector_id]
		sector.conflictLoyaltyGained = false
	end
end

function OnMsg.ConflictEnd(sector, _, playerAttacked, playerWon, autoResolve, isRetreat, startedFromMap)
	-- If you win in a conflict in a sector adjacent to a city sector that you own
	-- you get loyalty for that city.
	local allySquads = GetGroupedSquads(sector.Id, true, false, "no_retreating", "non_travelling")
	if playerWon then
		if sector.RunLoyaltyLogic then
			if (not playerAttacked and not startedFromMap) or not sector.conflictLoyaltyGained then
				local city = GetLoyaltyCityNearby(sector)
				
				assert(allySquads and #allySquads > 0)
				
				local nonMilitiaSquad = false
				for i, sq in ipairs(allySquads) do
					if not sq.militia then
						nonMilitiaSquad = true
					end
				end
				
				-- Militia won alone!
				if not nonMilitiaSquad then
					assert(autoResolve)
					CityModifyLoyalty(city, const.Loyalty.ConflictMilitiaOnlyWinBonus, T(469271409848, "Enemies cleared by militia"))
					sector.conflictLoyaltyGained = true
				else
					CityModifyLoyalty(city, const.Loyalty.ConflictWinBonus, T(133483288436, "Enemies cleared"))
					sector.conflictLoyaltyGained = true
				end
			end

			--world flip that has caused disable autoresolve should be cleared
			sector.autoresolve_disabled = false
		end
		
		-- Cancel units that have retreated, now that we've won. (219850)
		for i, squad in ipairs(allySquads) do
			for i, uId in ipairs(squad.units) do
				local ud = gv_UnitData[uId]
				if ud and ud.retreat_to_sector then
					CancelUnitRetreat(ud)
				end
			end
		end
		LocalCheckUnitsMapPresence()
	-- If you retreat (this also happens when losing an auto resolve)
	elseif isRetreat and sector.RunLoyaltyLogic then
		local city = GetLoyaltyCityNearby(sector)
		CityModifyLoyalty(city, const.Loyalty.ConflictRetreatPenalty, T(186425120178, "Retreat"))
		
		if not LostLoyaltyWithSectorsThisTick then LostLoyaltyWithSectorsThisTick = {} end
		LostLoyaltyWithSectorsThisTick[sector.Id] = true
		
	-- If you get defeated (regardless of whether militia got defeated or mercs)
	elseif not playerWon and (not allySquads or #allySquads == 0) and sector.RunLoyaltyLogic then
		local city = GetLoyaltyCityNearby(sector, "adjacent_only")
		CityModifyLoyalty(city, const.Loyalty.ConflictDefeatedLoyaltyLoss, T(703208874704, "Defeat"))
	end
end

function OpenSatelliteConflictDlg(context, openedBy)
	CreateRealTimeThread(function()
		WaitPlayingSetpiece()
		
		local satCon = GetDialog("SatelliteConflict")
		if satCon then
			-- This shouldn't happen, but better to handle it. Reopen the dialog to ensure we have the latest.
			-- One way this can happen is when triggering a conflict from a shortcut exit
			-- since reaching the sector and the sector center will happen back to back.
			-- Another way this happens is when going out of an underground sector into an overground conflict through sat view.
			if satCon.context.Id == context.Id then
				print("double conflict", context.Id)
				satCon:Close()
			end
			WaitMsg(satCon)
		end
		
		local popupHost = GetDialog("PDADialogSatellite")
		popupHost = popupHost and popupHost:ResolveId("idDisplayPopupHost")
		OpenDialog("SatelliteConflict", popupHost or GetInGameInterface(), context)
		
		-- Play the cool sound only when the conflict is
		-- initiated by the code, and not when it is opened by UI.
		if openedBy == "auto-open" then
			PlayFX("ConflictPanelOpen")
		else
			PlayFX("ConflictPanelOpenByPlayer")
		end
	end)
end

function OnMsg.UnitDieStart(unit, attacker)
	if unit:IsCivilian() and unit.Affiliation == "Civilian" and attacker then
		local attackerSide = IsKindOf(attacker, "DynamicSpawnLandmine") and attacker.team_side or attacker.team.side
		local playerSide = NetPlayerSide()
		
		local attackerIsPlayer = attackerSide == playerSide
		local attackerIsPlayerEnemy = SideIsEnemy(playerSide, attackerSide)
		if attackerIsPlayer or attackerIsPlayerEnemy then
			CivilianDeathPenalty()
		end
	end
end

GameVar("gv_CiviliansKilled", 0)
function OnMsg.OnKill(attacker, killedUnits)
	if IsMerc(attacker) then
		for _, unit in ipairs(killedUnits) do
			if unit:IsCivilian() and not unit.immortal then
				gv_CiviliansKilled = gv_CiviliansKilled + 1
			end
		end
	end
end

function DespawnUnitData(sectorId, class, despawnUnitToo)
	local found = table.filter(gv_UnitData, function(i, o)  
		local squad = o.Squad
		squad = squad and gv_Squads[squad]
		
		local sectorFilter = squad and squad.CurrentSector == sectorId
		if not squad then
			sectorFilter = g_Units[o.session_id] and gv_CurrentSectorId == sectorId
		end
		
		return o.class == class and sectorFilter
	end)

	local firstIdx = found and next(found)
	if not firstIdx then return end
	RemoveUnitFromSquad(found[firstIdx], despawnUnitToo and "despawn")
	if despawnUnitToo then
		LocalCheckUnitsMapPresence()
	end
end

function IsAutoResolveEnabled(sector)
	if sector.never_autoresolve then
		return false
	end

	if not sector.conflict then
		return false
	end

	if not sector.Map then
		return true
	end
	
	-- These are the squads that would be part of the conflict. (SatelliteConflict.lua)
	-- Auto resolve is always enabled if only militia squads will be part of the conflict.
	local alliesInConflict, enemySquads = GetSquadsInSector(sector.Id, "excludeTravelling", "includeMilitia", "excludeArriving")
	if not alliesInConflict or #alliesInConflict == 0 then
		return false
	end
	
	local onlyMilitia = true
	for i, s in ipairs(alliesInConflict) do
		if not s.militia then
			onlyMilitia = false
			break
		end
	end
	if onlyMilitia then
		return true
	end
	
	-- Losing auto resolve will retreat the squad
	-- so we allow auto resolve only when at least of the squads
	-- has a sector to retreat to (then all squads which dont have
	-- a valid retreat sector will inherit it from them in SatelliteRetreat)
	local anyHavePreviousSector = false
	for i, squad in ipairs(alliesInConflict) do
		anyHavePreviousSector = not squad.militia and squad.PreviousSector
		
		-- How?!?
		anyHavePreviousSector = anyHavePreviousSector and squad.PreviousSector ~= sector.Id
		
		if anyHavePreviousSector then break end
	end
	
	if not anyHavePreviousSector then
		return false
	end
	
	if sector.autoresolve_disabled then
		return false
	end
	
	if not enemySquads or #enemySquads == 0 then
		return false
	end
	
	return CanGoInMap(sector.Id) and not sector.ForceConflict
end

function OnMsg.ConflictEnd(sector)
	-- Check if player won
	if sector.Side ~= "player1" then return end
	
	-- Check if militia present
	local militia_squad_id = sector.militia_squad_id
	local militia_squad = gv_Squads[militia_squad_id]
	if not militia_squad or #(militia_squad.units or "") == 0 then return end	
	
	local quest = gv_Quests["05_TakeDownMajor"] and QuestGetState("05_TakeDownMajor")
	if not quest then return end
	SetQuestVar(quest, "LegionBeatenByMilitia", true)
end

function GetSatelliteConflictWarnings(squads)
	local woundedCount, tiredCount = 0, 0
	for _, squad in ipairs(squads) do
		for _, id in ipairs(squad.units) do
			local unit = gv_UnitData[id]
			if unit.Tiredness >= 1 then
				tiredCount = tiredCount + 1
			end
			if unit.HitPoints < MulDivRound(unit:GetInitialMaxHitPoints(), 50, 100) then
				woundedCount = woundedCount + 1
			end
		end
	end
	return woundedCount, tiredCount
end

function OnMsg.StartSatelliteGameplay()
	if ZuluAppliedSessionDataFixups.RemoveInvalidConflicts and not
		ZuluAppliedSessionDataFixups.RemoveInvalidConflicts_2 then
		if CampaignPauseReasons.SatelliteConflict and not AnyNonWaitingConflict() then
			ResumeCampaignTime("SatelliteConflict")
		end
		ZuluAppliedSessionDataFixups.RemoveInvalidConflicts_2 = true
	end
end

function SavegameSessionDataFixups.RemoveInvalidConflicts(data)
	-- Manually get squads in the sector as the data is not filled in yet at this point.
	-- Uses same logic as AddSquadToSectorList
	local function lSquadsInSector(sector)
		local ally, enemy, militia = {}, {}, {}
		
		local squads = GetGameVarFromSession(data, "gv_Squads")
		for _, squad in sorted_pairs(squads) do
			if squad.CurrentSector == sector.Id then
				if (squad.Side == "player1" or squad.Side == "ally") then
					if not squad.militia then
						ally[#ally + 1] = squad
					else	
						militia[#militia + 1] = squad
					end
				else
					enemy[#enemy + 1] = squad
				end
			end
		end
		
		return ally, enemy, militia
	end
	
	local sectors = GetGameVarFromSession(data, "gv_Sectors")
	local anyConflict

	for id, sector in pairs(sectors) do
		if sector.conflict then
			local ally, enemy, militia = lSquadsInSector(sector)
			if not next(ally) and (not next(militia) or not next(enemy)) then
				sector.conflict = false
			else
				anyConflict = true
			end
		end
	end

	if not anyConflict then
		data.game.PersistableCampaignPauseReasons["SatelliteConflict"] = nil
	end
end