File: missiondebrief.cpp

package info (click to toggle)
freespace2 24.2.0%2Brepack-1
  • links: PTS, VCS
  • area: non-free
  • in suites: forky, sid
  • size: 43,716 kB
  • sloc: cpp: 595,001; ansic: 21,741; python: 1,174; sh: 457; makefile: 248; xml: 181
file content (2627 lines) | stat: -rw-r--r-- 78,289 bytes parent folder | download
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
/*
 * Copyright (C) Volition, Inc. 1999.  All rights reserved.
 *
 * All source code herein is the property of Volition, Inc. You may not sell 
 * or otherwise commercially exploit the source or things you created based on the 
 * source.
 *
*/ 




#include "cfile/cfile.h"
#include "gamehelp/contexthelp.h"
#include "gamesequence/gamesequence.h"
#include "gamesnd/eventmusic.h"
#include "gamesnd/gamesnd.h"
#include "globalincs/alphacolors.h"
#include "globalincs/globals.h"
#include "graphics/font.h"
#include "iff_defs/iff_defs.h"
#include "io/key.h"
#include "io/timer.h"
#include "localization/localize.h"
#include "mission/missionbriefcommon.h"
#include "mission/missioncampaign.h"
#include "mission/missiongoals.h"
#include "mission/missiontraining.h"
#include "missionui/chatbox.h"
#include "missionui/missiondebrief.h"
#include "missionui/missionpause.h"
#include "missionui/missionscreencommon.h"
#include "network/multi.h"
#include "network/multi_campaign.h"
#include "network/multi_endgame.h"
#include "network/multi_kick.h"
#include "network/multi_pinfo.h"
#include "network/multimsgs.h"
#include "network/multiui.h"
#include "network/multiutil.h"
#include "osapi/osapi.h"
#include "parse/parselo.h"
#include "parse/sexp_container.h"
#include "pilotfile/pilotfile.h"
#include "playerman/player.h"
#include "popup/popup.h"
#include "ship/ship.h"
#include "sound/audiostr.h"
#include "sound/fsspeech.h"
#include "stats/medals.h"
#include "stats/stats.h"
#include "ui/uidefs.h"


#define MAX_TOTAL_DEBRIEF_LINES	200

#define TEXT_TYPE_NORMAL			1
#define TEXT_TYPE_RECOMMENDATION	2

#define DEBRIEF_NUM_STATS_PAGES	4
#define DEBRIEF_MISSION_STATS		0
#define DEBRIEF_MISSION_KILLS		1
#define DEBRIEF_ALLTIME_STATS		2
#define DEBRIEF_ALLTIME_KILLS		3

const int DEBRIEFING_FONT = font::FONT1;

extern float Brief_text_wipe_time_elapsed;

// 3rd coord is max width in pixels
int Debrief_title_coords[GR_NUM_RESOLUTIONS][3] = {
	{ // GR_640
		18, 118, 174
	},
	{ // GR_1024
		28, 193, 280
	}
};

int Debrief_text_wnd_coords[GR_NUM_RESOLUTIONS][4] = {
	{	// GR_640
		43, 140, 339, 303			
	},	
	{	// GR_1024
		69, 224, 535, 485		
	}
};

int Debrief_text_x2[GR_NUM_RESOLUTIONS] = {
	276,	// GR_640
	450	// GR_1024
};
	
int Debrief_stage_info_coords[GR_NUM_RESOLUTIONS][2] = {
	{	// GR_640
		379, 137		
	},	
	{	// GR_1024
		578, 224
	}
};

int Debrief_more_coords[GR_NUM_RESOLUTIONS][2] = {
	{	// GR_640
		323, 453	
	},
	{	// GR_1024
		323, 453	
	}
};

#define MULTI_LIST_TEAM_OFFSET					16		

int Debrief_multi_list_team_max_display[GR_NUM_RESOLUTIONS] = {
	9,	// GR_640
	12	// GR_1024
};

int Debrief_list_coords[GR_NUM_RESOLUTIONS][4] = {
	{	// GR_640
		416, 280, 195, 101
	},
	{	// GR_1024
		666, 448, 312, 162
	}
};

int Debrief_award_wnd_coords[GR_NUM_RESOLUTIONS][2] = {
	{	// GR_640
		411, 126
	},
	{	// GR_1024
		658, 203	
	}
};


int Debrief_award_coords[GR_NUM_RESOLUTIONS][2] = {
	{	// GR_640
		416, 140
	},
	{	// GR_1024
		666, 224	
	}
};

// 0=x, 1=y, 2=width of the field
int Debrief_medal_text_coords[GR_NUM_RESOLUTIONS][3] = {
	{	// GR_640
		423, 247, 189
	},
	{	// GR_1024
		666, 333, 67
	}
};

// 0=x, 1=y, 2=height of the field
int Debrief_award_text_coords[GR_NUM_RESOLUTIONS][3] = {
	{	// GR_640
		416, 210, 42
	},
	{	// GR_1024
		666, 333, 67
	}
};

// 0 = with medal
// 1 = without medal (text will use medal space)
#define DB_WITH_MEDAL		0
#define DB_WITHOUT_MEDAL	1
int Debrief_award_text_width[GR_NUM_RESOLUTIONS][2] = {
	{	// GR_640
		123, 203
	},
	{	// GR_1024
		196, 312	
	}
};

const char *Debrief_single_name[GR_NUM_RESOLUTIONS] = {
	"DebriefSingle",		// GR_640
	"2_DebriefSingle"		// GR_1024
};
const char *Debrief_multi_name[GR_NUM_RESOLUTIONS] = {
	"DebriefMulti",		// GR_640
	"2_DebriefMulti"		// GR_1024
};
const char *Debrief_mask_name[GR_NUM_RESOLUTIONS] = {
	"Debrief-m",			// GR_640
	"2_Debrief-m"			// GR_1024
};

#define NUM_BUTTONS	18
#define NUM_TABS		2

#define DEBRIEF_TAB				0
#define STATS_TAB					1
#define TEXT_SCROLL_UP			2
#define TEXT_SCROLL_DOWN		3
#define REPLAY_MISSION			4
#define RECOMMENDATIONS			5
#define FIRST_STAGE				6
#define PREV_STAGE				7
#define NEXT_STAGE				8
#define LAST_STAGE				9
#define MULTI_PINFO_POPUP		10
#define MULTI_KICK				11
#define MEDALS_BUTTON			12
#define PLAYER_SCROLL_UP		13
#define PLAYER_SCROLL_DOWN		14
#define HELP_BUTTON				15
#define OPTIONS_BUTTON			16
#define ACCEPT_BUTTON			17

#define REPEAT	1

//XSTR:OFF
const char* Debrief_loading_bitmap_fname[GR_NUM_RESOLUTIONS] = {
	"PleaseWait",		// GR_640
	"2_PleaseWait"		// GR_1024
};

//XSTR:ON

typedef struct {
	char	text[NAME_LENGTH+1];	// name of ship type with a colon
	int	num;						// how many ships of this type player has killed
} debrief_stats_kill_info;

typedef struct {
	int net_player_index;	// index into Net_players[] array
	int rank_bitmap;			// bitmap id for rank
	char callsign[CALLSIGN_LEN];
} debrief_multi_list_info;

static ui_button_info Buttons[GR_NUM_RESOLUTIONS][NUM_BUTTONS] = {
	{ // GR_640
		ui_button_info("DB_00",		6,		1,		37,	7,		0),		// debriefing
		ui_button_info("DB_01",		6,		21,	37,	23,	1),		// statistics
		ui_button_info("DB_02",		1,		195,	-1,	-1,	2),		// scroll stats up
		ui_button_info("DB_03",		1,		236,	-1,	-1,	3),		// scroll stats down
		ui_button_info("DB_04",		1,		428,	49,	447,	4),		// replay mission
		ui_button_info("DB_05",		17,	459,	49,	464,	5),		// recommendations
		ui_button_info("DB_06",		323,	454,	-1,	-1,	6),		// first page
		ui_button_info("DB_07",		348,	454,	-1,	-1,	7),		// prev page
		ui_button_info("DB_08",		372,	454,	-1,	-1,	8),		// next page
		ui_button_info("DB_09",		396,	454,	-1,	-1,	9),		// last page
		ui_button_info("DB_10",		441,	384,	433,	413,	10),		// pilot info
		ui_button_info("DB_11",		511,	384,	510,	413,	11),		// kick
		ui_button_info("DB_12",		613,	226,	-1,	-1,	12),		// medals
		ui_button_info("DB_13",		615,	329,	-1,	-1,	13),		// scroll pilots up
		ui_button_info("DB_14",		615,	371,	-1,	-1,	14),		// scroll pilots down
		ui_button_info("DB_15",		538,	431,	500,	440,	15),		// help
		ui_button_info("DB_16",		538,	455,	479,	464,	16),		// options
		ui_button_info("DB_17",		573,	432,	572,	413,	17),		// accept
	},
	{ // GR_1024
		ui_button_info("2_DB_00",		10,	1,		59,	12,	0),		// debriefing
		ui_button_info("2_DB_01",		10,	33,	59,	37,	1),		// statistics
		ui_button_info("2_DB_02",		1,		312,	-1,	-1,	2),		// scroll stats up
		ui_button_info("2_DB_03",		1,		378,	-1,	-1,	3),		// scroll stats down
		ui_button_info("2_DB_04",		1,		685,	79,	715,	4),		// replay mission
		ui_button_info("2_DB_05",		28,	735,	79,	743,	5),		// recommendations
		ui_button_info("2_DB_06",		517,	726,	-1,	-1,	6),		// first page
		ui_button_info("2_DB_07",		556,	726,	-1,	-1,	7),		// prev page
		ui_button_info("2_DB_08",		595,	726,	-1,	-1,	8),		// next page
		ui_button_info("2_DB_09",		633,	726,	-1,	-1,	9),		// last page
		ui_button_info("2_DB_10",		706,	615,	700,	661,	10),		// pilot info
		ui_button_info("2_DB_11",		817,	615,	816,	661,	11),		// kick
		ui_button_info("2_DB_12",		981,	362,	-1,	-1,	12),		// medals
		ui_button_info("2_DB_13",		984,	526,	-1,	-1,	13),		// scroll pilots up
		ui_button_info("2_DB_14",		984,	594,	-1,	-1,	14),		// scroll pilots down
		ui_button_info("2_DB_15",		861,	689,	801,	705,	15),		// help
		ui_button_info("2_DB_16",		861,	728,	777,	744,	16),		// options
		ui_button_info("2_DB_17",		917,	692,	917,	692,	17),		// accept
	}
};

// text
#define NUM_DEBRIEF_TEXT				10
#define MP_TEXT_INDEX_1					4
#define MP_TEXT_INDEX_2					5
#define MP_TEXT_INDEX_3					6
UI_XSTR Debrief_strings[GR_NUM_RESOLUTIONS][NUM_DEBRIEF_TEXT] = {
	{ // GR_640
		{ "Debriefing",		804,		37,	7,		UI_XSTR_COLOR_GREEN,	-1,	&Buttons[0][DEBRIEF_TAB].button },
		{ "Statistics",		1333,		37,	26,	UI_XSTR_COLOR_GREEN,	-1,	&Buttons[0][STATS_TAB].button },
		{ "Replay Mission",	444,		49,	447,	UI_XSTR_COLOR_PINK,	-1,	&Buttons[0][REPLAY_MISSION].button },
		{ "Recommendations",	1334,		49,	464,	UI_XSTR_COLOR_GREEN,	-1,	&Buttons[0][RECOMMENDATIONS].button },
		{ "Pilot",				1310,		433,	413,	UI_XSTR_COLOR_GREEN,	-1,	&Buttons[0][MULTI_PINFO_POPUP].button },
		{ "Info",				1311,		433,	423,	UI_XSTR_COLOR_GREEN,	-1,	&Buttons[0][MULTI_PINFO_POPUP].button },
		{ "Kick",				1266,		510,	413,	UI_XSTR_COLOR_GREEN,	-1,	&Buttons[0][MULTI_KICK].button },
		{ "Help",				928,		500,	440,	UI_XSTR_COLOR_GREEN,	-1,	&Buttons[0][HELP_BUTTON].button },
		{ "Options",			1036,		479,	464,	UI_XSTR_COLOR_GREEN,	-1,	&Buttons[0][OPTIONS_BUTTON].button },
		{ "Accept",				1035,		572,	413,	UI_XSTR_COLOR_PINK,	-1,	&Buttons[0][ACCEPT_BUTTON].button },
	},
	{ // GR_1024
		{ "Debriefing",		804,		59,	12,	UI_XSTR_COLOR_GREEN,	-1,	&Buttons[1][DEBRIEF_TAB].button },
		{ "Statistics",		1333,		59,	47,	UI_XSTR_COLOR_GREEN,	-1,	&Buttons[1][STATS_TAB].button },
		{ "Replay Mission",	444,		79,	715,	UI_XSTR_COLOR_PINK,	-1,	&Buttons[1][REPLAY_MISSION].button },
		{ "Recommendations",	1334,		79,	743,	UI_XSTR_COLOR_GREEN,	-1,	&Buttons[1][RECOMMENDATIONS].button },
		{ "Pilot",				1310,		700,	661,	UI_XSTR_COLOR_GREEN,	-1,	&Buttons[1][MULTI_PINFO_POPUP].button },
		{ "Info",				1311,		700,	679,	UI_XSTR_COLOR_GREEN,	-1,	&Buttons[1][MULTI_PINFO_POPUP].button },
		{ "Kick",				1266,		816,	661,	UI_XSTR_COLOR_GREEN,	-1,	&Buttons[1][MULTI_KICK].button },
		{ "Help",				928,		801,	705,	UI_XSTR_COLOR_GREEN,	-1,	&Buttons[1][HELP_BUTTON].button },
		{ "Options",			1036,		780,	744,	UI_XSTR_COLOR_GREEN,	-1,	&Buttons[1][OPTIONS_BUTTON].button },
		{ "Accept",				1035,		917,	672,	UI_XSTR_COLOR_PINK,	-1,	&Buttons[1][ACCEPT_BUTTON].button },
	}
};


char Debrief_current_callsign[CALLSIGN_LEN+10];
player *Debrief_player;

static UI_WINDOW Debrief_ui_window;
static UI_BUTTON List_region;
static int Background_bitmap;					// bitmap for the background of the debriefing
static int Award_bg_bitmap;
static int Debrief_multi_loading_bitmap;
static int Rank_bitmap;
static int Medal_bitmap;
static int Badge_bitmap;

int Promoted;
static int Debrief_accepted;
int Turned_traitor;
int Must_replay_mission;

static int Current_mode;
static int New_mode;
static int Recommend_active;
static int Award_active;
static int Text_offset;
static int Num_text_lines = 0;

static int Debrief_inited = 0;
static int New_stage;
static int Current_stage;
static int Num_stages;
static int Num_debrief_stages;
static int Stage_voice = -1;
static UI_TIMESTAMP Debrief_music_timeout;

static int Multi_list_size;
static int Multi_list_offset;

int Debrief_overlay_id;

int Debrief_multi_stages_loaded = 0;
int Debrief_multi_voice_loaded = 0;

// static int Debrief_voice_ask_for_cd;

// voice id's for debriefing text
static int Debrief_voices[MAX_DEBRIEF_STAGES];

#define DEBRIEF_VOICE_DELAY 400				// time to delay voice playback when a new stage starts
static UI_TIMESTAMP Debrief_cue_voice;		// timestamp to cue the playback of the voice
static int Debrief_first_voice_flag = 1;	// used to delay the first voice playback extra long

static int Debriefing_paused = 0;

int Max_debrief_Lines;

// pointer used for getting to debriefing information
debriefing	Traitor_debriefing;				// used when player is a traitor

// pointers to the active stages for this debriefing
static debrief_stage *Debrief_stages[MAX_DEBRIEF_STAGES];
debrief_stage Promotion_stage, Badge_stage;
static debrief_stats_kill_info *Debrief_stats_kills = NULL;
static debrief_multi_list_info Multi_list[MAX_PLAYERS];
int Multi_list_select;

// flag indicating if we should display info for the given player (in multiplayer)
int Debrief_should_show_popup = 1;

// already shown skip mission popup?
static int Debrief_skip_popup_already_shown = 0;

void debrief_text_init();
bool debrief_can_accept();
void debrief_kick_selected_player();


// promotion voice selection stuff
#define NUM_VOLITION_CAMPAIGNS	1
typedef struct {
	char  campaign_name[32];
	int	num_missions;
} v_campaign;

v_campaign Volition_campaigns[NUM_VOLITION_CAMPAIGNS] = {
	{
		BUILTIN_CAMPAIGN,		// the only campaign for now, but this leaves room for a mission pack
		35						// make sure this is equal to the  number of missions you gave in the corresponding Debrief_promotion_voice_mapping
	}
};


// data for which voice goes w/ which mission
typedef struct voice_map {
	char  mission_file[32];
	int	persona_index;
} voice_map;

voice_map Debrief_promotion_voice_mapping[NUM_VOLITION_CAMPAIGNS][MAX_CAMPAIGN_MISSIONS] = {
	{		// FreeSpace2 campaign 
		{ "SM1-01.fs2",			1 },
		{ "SM1-02.fs2",			1 },
		{ "SM1-03.fs2",			1 },
		{ "SM1-04.fs2",			2 },
		{ "SM1-05.fs2",			2 },
		{ "SM1-06.fs2",			2 },
		{ "SM1-07.fs2",			2 },
		{ "SM1-08.fs2",			3 },
		{ "SM1-09.fs2",			3 },
		{ "SM1-10.fs2",			3 },

		{ "SM2-01.fs2",			6 },
		{ "SM2-02.fs2",			6 },
		{ "SM2-03.fs2",			6 },
		{ "SM2-04.fs2",			7 },
		{ "SM2-05.fs2",			7 },
		{ "SM2-06.fs2",			7 },
		{ "SM2-07.fs2",			8 },
		{ "SM2-08.fs2",			8 },
		{ "SM2-09.fs2",			8 },
		{ "SM2-10.fs2",			8 },

		{ "SM3-01.fs2",			8 },
		{ "SM3-02.fs2",			8 },
		{ "SM3-03.fs2",			8 },
		{ "SM3-04.fs2",			8 },
		{ "SM3-05.fs2",			8 },
		{ "SM3-06.fs2",			9 },
		{ "SM3-07.fs2",			9 },
		{ "SM3-08.fs2",			9 },
		{ "SM3-09.fs2",			9 },
		{ "SM3-10.fs2",			9 },			// no debriefing for 3-10
		
		{ "loop1-1.fs2",			4 },
		{ "loop1-2.fs2",			4 },
		{ "loop1-3.fs2",			5 },
		{ "loop2-1.fs2",			4 },
		{ "loop2-2.fs2",			4 }
	}
};

static const char* Debrief_award_background[GR_NUM_RESOLUTIONS] = {
	"DebriefAward",
	"2_DebriefAward"
};

#define AWARD_TEXT_MAX_LINES				5
#define AWARD_TEXT_MAX_LINE_LENGTH		128
char Debrief_award_text[AWARD_TEXT_MAX_LINES][AWARD_TEXT_MAX_LINE_LENGTH];
int Debrief_award_text_num_lines = 0;



// prototypes, you know you love 'em
void debrief_add_award_text(const char *str);
void debrief_award_text_clear();
void debrief_replace_stage_text(debrief_stage &stage);



// functions
const char *debrief_tooltip_handler(const char *str)
{
	if (!stricmp(str, NOX("@.Medal"))) {
		if (Award_active){
			return XSTR( "Medal", 435);
		}

	} else if (!stricmp(str, NOX("@.Rank"))) {
		if (Award_active){
			return XSTR( "Rank", 436);
		}

	} else if (!stricmp(str, NOX("@.Badge"))) {
		if (Award_active){
			return XSTR( "Badge", 437);
		}

	} else if (!stricmp(str, NOX("@Medal"))) {
		if (Medal_bitmap >= 0){
			return Medals[Player->stats.m_medal_earned].get_display_name();
		}

	} else if (!stricmp(str, NOX("@Rank"))) {
		if (Rank_bitmap >= 0){
			return Ranks[Promoted].name;
		}

	} else if (!stricmp(str, NOX("@Badge"))) {
		if (Badge_bitmap >= 0){
			return Medals[Player->stats.m_badge_earned.back()].get_display_name();
		}
	}

	return NULL;
}

// initialize the array of handles to the different voice streams
void debrief_voice_init()
{
	int i;

	for (i=0; i<MAX_DEBRIEF_STAGES; i++) {
		Debrief_voices[i] = -1;
	}
}

void debrief_load_voice_file(int voice_num, char *name)
{
	int load_attempts = 0;
	while(1) {

		if ( load_attempts++ > 5 ) {
			break;
		}

		Debrief_voices[voice_num] = audiostream_open( name, ASF_VOICE );
		if ( Debrief_voices[voice_num] >= 0 ) {
			break;
		}

		// Don't bother to ask for the CD in multiplayer
		if ( Game_mode & GM_MULTIPLAYER ) {
			break;
		}

	}
}

// open and pre-load the stream buffers for the different voice streams
void debrief_voice_load_all()
{
	int i;

	// Debrief_voice_ask_for_cd = 1;

	for ( i=0; i<Num_debrief_stages; i++ ) {
		if ( strlen(Debrief_stages[i]->voice) <= 0 ) {
			continue;
		}
		if ( strnicmp(Debrief_stages[i]->voice, NOX("none"), 4) != 0 ) {
			debrief_load_voice_file(i, Debrief_stages[i]->voice);
//			Debrief_voices[i] = audiostream_open(Debrief_stages[i]->voice, ASF_VOICE);
		}
	}
}

// close all the briefing voice streams
void debrief_voice_unload_all()
{
	int i;

	for ( i=0; i<MAX_DEBRIEF_STAGES; i++ ) {
		if ( Debrief_voices[i] != -1 ) {
			audiostream_close_file(Debrief_voices[i], 0);
			Debrief_voices[i] = -1;
		}
	}
}

// start playback of the voice for a particular briefing stage
void debrief_voice_play()
{
	if (!Briefing_voice_enabled || (Current_mode != DEBRIEF_TAB)){
		return;
	}

	// no more stages?  We are done then.
	if (Stage_voice >= Num_debrief_stages){
		return;
	}

	// if in delayed start, see if delay has elapsed and start voice if so
	if (Debrief_cue_voice.isValid()) {
		if (!ui_timestamp_elapsed(Debrief_cue_voice)){
			return;
		}

		Stage_voice++;  // move up to next voice
		if ((Stage_voice < Num_debrief_stages) && (Debrief_voices[Stage_voice] >= 0)) {
			audiostream_play(Debrief_voices[Stage_voice], Master_voice_volume, 0);
			Debrief_cue_voice = UI_TIMESTAMP::invalid();  // indicate no longer in delayed start checking
		}

		return;
	}

	// see if voice is still playing.  If so, do nothing yet.
	if ((Stage_voice >= 0) && audiostream_is_playing(Debrief_voices[Stage_voice])){
		return;
	}

	// set voice to play in a little while from now.
	Debrief_cue_voice = ui_timestamp(DEBRIEF_VOICE_DELAY);
}

// stop playback of the voice for a particular briefing stage
void debrief_voice_stop()
{
	if ((Stage_voice < 0) || (Stage_voice > Num_debrief_stages) || (Debrief_voices[Stage_voice] < 0))
		return;

	audiostream_stop(Debrief_voices[Stage_voice], 1, 0);  // stream is automatically rewound
	Stage_voice = -1;

	fsspeech_stop();
}

extern int Briefing_music_handle;

void debrief_pause()
{
	if (Debriefing_paused)
		return;

	Debriefing_paused = 1;

	if (Briefing_music_handle >= 0) {
		audiostream_pause(Briefing_music_handle);
	}

	if ((Stage_voice < 0) || (Stage_voice > Num_debrief_stages) || (Debrief_voices[Stage_voice] < 0))
		return;

	audiostream_pause(Debrief_voices[Stage_voice]);

	fsspeech_pause(true);
}

void debrief_unpause()
{
	if (!Debriefing_paused)
		return;

	Debriefing_paused = 1;

	if (Briefing_music_handle >= 0) {
		audiostream_unpause(Briefing_music_handle);
	}

	if ((Stage_voice < 0) || (Stage_voice > Num_debrief_stages) || (Debrief_voices[Stage_voice] < 0))
		return;

	audiostream_unpause(Debrief_voices[Stage_voice]);

	fsspeech_pause(false);
}

// function to deal with inserting possible promition and badge stages into the debriefing
// on the clients
void debrief_multi_fixup_stages()
{
	int i;

	// possibly insert the badge stage first, them the promotion stage since they are
	// inserted at the front of the debrief stages.
	if ( Badge_bitmap >= 0 ) {
		// move all stages forward one.  Don't 
		for ( i = Num_debrief_stages; i > 0; i-- ) {
			Debrief_stages[i] = Debrief_stages[i-1];
		}
		Debrief_stages[0] = &Badge_stage;
		Num_debrief_stages++;
	}

	if ( Promoted >= 0) {
		// move all stages forward one
		for ( i = Num_debrief_stages; i > 0; i-- ) {
			Debrief_stages[i] = Debrief_stages[i-1];
		}
		Debrief_stages[0] = &Promotion_stage;
		Num_debrief_stages++;
	}
}


// function called from multiplayer clients to set up the debriefing information for them
// (sent from the server).  
void debrief_set_multi_clients( int stage_count, int active_stages[] )
{
	int i;

	// set up the right briefing for this guy
	if(MULTI_TEAM){
		Debriefing = &Debriefings[Net_player->p_info.team];
	} else {
		Debriefing = &Debriefings[0];			
	}

	// see if this client was promoted -- if so, then add the first stage.
	Num_debrief_stages = 0;

	// set the pointers to the debriefings for this client
	for (i = 0; i < stage_count; i++) {
		Debrief_stages[Num_debrief_stages++] = &Debriefing->stages[active_stages[i]];
		// in multi, debriefing text replacement must occur client-side
		// update most recently added stage only, in case replacement has side effects
		debrief_replace_stage_text(*Debrief_stages[Num_debrief_stages - 1]);
	}

	Debrief_multi_stages_loaded = 1;
}

// evaluate all stages for all teams.  Server of a multiplayer game will have to send that
// information to all clients after leaving this screen.
void debrief_multi_server_stuff()
{
	debriefing *debriefp;

	int stage_active[MAX_TVT_TEAMS][MAX_DEBRIEF_STAGES], *stages[MAX_TVT_TEAMS];
	int i, j, num_stages, stage_count[MAX_TVT_TEAMS];

	memset( stage_active, 0, sizeof(stage_active) );

	for (i=0; i<Num_teams; i++) {
		debriefp = &Debriefings[i];
		num_stages = 0;
		stages[i] = stage_active[i];
		for (j=0; j<debriefp->num_stages; j++) {
			if ( eval_sexp(debriefp->stages[j].formula) ) {
				stage_active[i][num_stages] = j;
				num_stages++;
			}
		}

		stage_count[i] = num_stages;
	}

	// if we're in campaign mode, evaluate campaign stuff
	if (Netgame.campaign_mode == MP_CAMPAIGN) {
		multi_campaign_eval_debrief();
	}

	// send the information to all clients.
	send_debrief_info( stage_count, stages );
}


// --------------------------------------------------------------------------------------
//	debrief_set_stages_and_multi_stuff()
//
// Set up the active stages for this debriefing
//
// returns:		number of active debriefing stages
//
int debrief_set_stages_and_multi_stuff()
{
	int i;
	debriefing	*debriefp;

	if ( MULTIPLAYER_CLIENT ) {
		return 0;
	}

	Num_debrief_stages = 0;

	if ( Game_mode & GM_MULTIPLAYER ) {
		debrief_multi_server_stuff();
	}

	// check to see if player is a traitor (looking at his team).  If so, use the special
	// traitor debriefing.  Only done in single player
	debriefp = Debriefing;
	if ( !(Game_mode & GM_MULTIPLAYER) ) {
		// although the no traitor flag check seems redundant it allows the mission designer to turn the traitor
		// debriefing off before the mission ends and supply one themselves 
		if ((Player_ship->team == Iff_traitor) && !(The_mission.flags[Mission::Mission_Flags::No_traitor]))
			debriefp = &Traitor_debriefing;
	}

	Num_debrief_stages = 0;
	if (Promoted >= 0) {
		Debrief_stages[Num_debrief_stages++] = &Promotion_stage;
	}

	if (Badge_bitmap >= 0) {
		Debrief_stages[Num_debrief_stages++] = &Badge_stage;
	}

	for (i=0; i<debriefp->num_stages; i++) {
		if (eval_sexp(debriefp->stages[i].formula) == SEXP_TRUE) {
			// replacement in single-player and for host/server in multi
			debrief_replace_stage_text(debriefp->stages[i]);
			Debrief_stages[Num_debrief_stages++] = &debriefp->stages[i];
		}
	}

	return Num_debrief_stages;
}

// init the buttons that are specific to the debriefing screen
void debrief_buttons_init()
{
	ui_button_info *b;
	int i;

	for ( i=0; i<NUM_BUTTONS; i++ ) {
		b = &Buttons[gr_screen.res][i];
		b->button.create( &Debrief_ui_window, "", b->x, b->y, 60, 30, 0 /*b->flags & REPEAT*/, 1 );
		// set up callback for when a mouse first goes over a button
		b->button.set_highlight_action( common_play_highlight_sound );
		b->button.set_bmaps(b->filename);
		b->button.link_hotspot(b->hotspot);
	}

	// add all xstrs
	for(i=0; i<NUM_DEBRIEF_TEXT; i++){
		// multiplayer specific text
		if((i == MP_TEXT_INDEX_1) || (i == MP_TEXT_INDEX_2) || (i == MP_TEXT_INDEX_3)){
			// only add if in multiplayer mode
			if(Game_mode & GM_MULTIPLAYER){
				Debrief_ui_window.add_XSTR(&Debrief_strings[gr_screen.res][i]);
			}
		} 
		// all other text
		else {
			Debrief_ui_window.add_XSTR(&Debrief_strings[gr_screen.res][i]);
		}
	}
	
	// set up hotkeys for buttons so we draw the correct animation frame when a key is pressed
	Buttons[gr_screen.res][NEXT_STAGE].button.set_hotkey(KEY_RIGHT);
	Buttons[gr_screen.res][PREV_STAGE].button.set_hotkey(KEY_LEFT);
	Buttons[gr_screen.res][LAST_STAGE].button.set_hotkey(KEY_SHIFTED | KEY_RIGHT);
	Buttons[gr_screen.res][FIRST_STAGE].button.set_hotkey(KEY_SHIFTED | KEY_LEFT);
	Buttons[gr_screen.res][TEXT_SCROLL_UP].button.set_hotkey(KEY_UP);
	Buttons[gr_screen.res][TEXT_SCROLL_DOWN].button.set_hotkey(KEY_DOWN);
	Buttons[gr_screen.res][ACCEPT_BUTTON].button.set_hotkey(KEY_CTRLED+KEY_ENTER);

	// if in multiplayer, disable the button for all players except the host
	// also disable for squad war matches
	if(Game_mode & GM_MULTIPLAYER){
		if((Netgame.type_flags & NG_TYPE_SW) || !(Net_player->flags & NETINFO_FLAG_GAME_HOST)){
			Buttons[gr_screen.res][REPLAY_MISSION].button.disable();
		}
	}
}

// --------------------------------------------------------------------------------------
//	debrief_ui_init()
//
void debrief_ui_init()
{
	// init ship selection masks and buttons
	common_set_interface_palette("DebriefPalette");		// set the interface palette
	Debrief_ui_window.create( 0, 0, gr_screen.max_w_unscaled, gr_screen.max_h_unscaled, 0 );
	Debrief_ui_window.set_mask_bmap(Debrief_mask_name[gr_screen.res]);
	Debrief_ui_window.tooltip_handler = debrief_tooltip_handler;
	debrief_buttons_init();

	// load in help overlay bitmap	
	Debrief_overlay_id = help_overlay_get_index(DEBRIEFING_OVERLAY);
	help_overlay_set_state(Debrief_overlay_id,gr_screen.res,0);

	if ( Game_mode & GM_MULTIPLAYER ) {
		// close down any old instances of the chatbox
		chatbox_close();

		// create the new one
		chatbox_create();
		List_region.create(&Debrief_ui_window, "", Debrief_list_coords[gr_screen.res][0], Debrief_list_coords[gr_screen.res][1], Debrief_list_coords[gr_screen.res][2], Debrief_list_coords[gr_screen.res][3], 0, 1);
		List_region.hide();

	}

	Background_bitmap = mission_ui_background_load(Debriefing->background[gr_screen.res], Debrief_single_name[gr_screen.res], Debrief_multi_name[gr_screen.res]);

	if ( Background_bitmap < 0 ) {
		Warning(LOCATION, "Could not load the background bitmap for debrief screen");
	}

	Award_bg_bitmap = bm_load(Debrief_award_background[gr_screen.res]);
	Debrief_multi_loading_bitmap = bm_load(Debrief_loading_bitmap_fname[gr_screen.res]);
}

// Goober5000
int debrief_find_persona_index()
{
	int i, j;

	if ((Campaign.current_mission >= 0) && (Campaign.missions[Campaign.current_mission].name))
	{
		// Goober5000 - first see if the campaign supplied a persona index
		// (0 means use the Volition default)
		if (Campaign.missions[Campaign.current_mission].debrief_persona_index != 0)
			return Campaign.missions[Campaign.current_mission].debrief_persona_index;

		// search through all official campaigns for our current campaign
		for (i = 0; i < NUM_VOLITION_CAMPAIGNS; i++)
		{
			if (!stricmp(Campaign.filename, Volition_campaigns[i].campaign_name))
			{
				// now search through the mission filenames
				for (j = 0; j < Volition_campaigns[i].num_missions; j++)
				{
					// found it!
					if (!stricmp(Campaign.missions[Campaign.current_mission].name, Debrief_promotion_voice_mapping[i][j].mission_file))
					{
						return Debrief_promotion_voice_mapping[i][j].persona_index;
					}
				}
			}
		}
	}

	// not found
	return -1;
}

// Goober5000
// V sez: "defaults to number 9 (Petrarch) for non-volition missions
// this is an ugly, nasty, hateful way of doing this, but it saves us changing the missions at this point"
void debrief_choose_voice(char *voice_dest, size_t buf_size, char *voice_base, int persona_index, int default_to_base = 0)
{
	if (persona_index >= 0)
	{
		// get voice file, also check for too long base file names via the return value of snprintf
		if (snprintf(voice_dest, buf_size, NOX("%d_%s"), persona_index, voice_base) < static_cast<int>(buf_size))
		{
			// if it exists, we're done
			if (cf_exists_full_ext(voice_dest, CF_TYPE_VOICE_DEBRIEFINGS, NUM_AUDIO_EXT, audio_ext_list))
				return;
		}

	}

	// that didn't work, so use the default

	// use the base file; don't prepend anything to it
	if (default_to_base)
	{
		strncpy(voice_dest, voice_base, buf_size);
	}
	// default to Petrarch
	else
	{
		strncpy(voice_dest, "9_", buf_size);
		strncat(voice_dest, voice_base, buf_size-2);
	}
	// Ensure null terminator
	voice_dest[buf_size-1] = '\0';
}

void debrief_choose_medal_variant(char *buf, int medal_earned, int zero_based_version_index)
{
	Assert(buf != NULL && medal_earned >= 0 && zero_based_version_index >= 0);

	// start with the regular file name, adapted for resolution
	sprintf(buf, NOX("%s%s"), Resolution_prefixes[gr_screen.res], Medals[medal_earned].debrief_bitmap);

	// if the medal has multiple versions, we may want to choose a specific bitmap
	char *p = strstr(buf, "##");
	if (p != NULL)
	{
		int version;
		char number[8];

		// possible to earn more than we have variants for
		if (zero_based_version_index >= Medals[medal_earned].num_versions)
			version = Medals[medal_earned].num_versions - 1;
		else
			version = zero_based_version_index;

		// also, this is dumb
		if (Medals[medal_earned].version_starts_at_1)
			version++;

		sprintf(number, NOX("%.2d"), version);
		Assert(strlen(number) == 2);
		strncpy(p, number, 2);
	}
}

void debrief_award_init()
{
	char buf[80];

	Rank_bitmap = -1; 
	Medal_bitmap = -1;
	Badge_bitmap = -1;
	Promoted = -1;

	// be sure there are no old award texts floating around
	debrief_award_text_clear();

	// handle medal earned
	if ( Player->stats.m_medal_earned != -1 ) {
		debrief_choose_medal_variant(buf, Player->stats.m_medal_earned, Player->stats.medal_counts[Player->stats.m_medal_earned] - 1);
		Medal_bitmap = bm_load(buf);

		debrief_add_award_text(Medals[Player->stats.m_medal_earned].get_display_name());
	}
	
	// handle promotions
	if ( Player->stats.m_promotion_earned != -1 ) {
		Promoted = Player->stats.m_promotion_earned;
		debrief_choose_medal_variant(buf, Rank_medal_index, Promoted);
		Rank_bitmap = bm_load(buf);

		// see if we have a persona
		int persona_index = The_mission.debriefing_persona;

		// use persona-specific promotion text if it exists; otherwise, use default
		if (Ranks[Promoted].promotion_text.find(persona_index) != Ranks[Promoted].promotion_text.end()) {
			Promotion_stage.text = Ranks[Promoted].promotion_text[persona_index];
		} else {
			Promotion_stage.text = Ranks[Promoted].promotion_text[-1];
		}
		Promotion_stage.recommendation_text = "";

		// choose appropriate promotion voice for this mission
		debrief_choose_voice(Promotion_stage.voice, sizeof(Promotion_stage.voice), Ranks[Promoted].promotion_voice_base, persona_index);

		debrief_add_award_text(get_rank_display_name(&Ranks[Promoted]).c_str());
	}

	// handle badge earned
	// only grant badge if earned and allowed.  (no_promotion really means no promotion and no badges)
	if ( Player->stats.m_badge_earned.size() ) {
		debrief_choose_medal_variant(buf, Player->stats.m_badge_earned.back(), Player->stats.medal_counts[Player->stats.m_badge_earned.back()] - 1);
		Badge_bitmap = bm_load(buf);

		// see if we have a persona
		int persona_index = The_mission.debriefing_persona;

		// use persona-specific badge text if it exists; otherwise, use default
		if (Medals[Player->stats.m_badge_earned.back()].promotion_text.find(persona_index) != Medals[Player->stats.m_badge_earned.back()].promotion_text.end()) {
			Badge_stage.text = Medals[Player->stats.m_badge_earned.back()].promotion_text[persona_index];
		} else {
			Badge_stage.text = Medals[Player->stats.m_badge_earned.back()].promotion_text[-1];
		}
		Badge_stage.recommendation_text = "";

		// choose appropriate badge voice for this mission
		debrief_choose_voice(Badge_stage.voice, sizeof(Badge_stage.voice), Medals[Player->stats.m_badge_earned.back()].voice_base, persona_index);

		debrief_add_award_text(Medals[Player->stats.m_badge_earned.back()].get_display_name());
	}

	if ((Rank_bitmap >= 0) || (Medal_bitmap >= 0) || (Badge_bitmap >= 0)) {
		Award_active = 1;
	} else {
		Award_active = 0;
	}
}

// debrief_traitor_init() initializes local data which could be used if the player leaves the 
// mission a traitor.  The same debriefing always gets played
void debrief_traitor_init()
{
	Debrief_accepted = 0;
	Turned_traitor = Must_replay_mission = 0;

	if (Player_ship->team == Iff_traitor) {
		Turned_traitor = 1;

		// if traitor, set up persona-specific traitor debriefing
		auto stagep = &Traitor_debriefing.stages[0];
		
		// see if we are using a traitor override
		if (The_mission.traitor_override != nullptr) {
			stagep->text = The_mission.traitor_override->text;
			strcpy_s(stagep->voice, The_mission.traitor_override->voice_filename);
			stagep->recommendation_text = The_mission.traitor_override->recommendation_text;
		} else {
			// see if we have a persona
			int persona_index = The_mission.debriefing_persona;

			// use persona-specific traitor text if it exists; otherwise, use default
			if (Traitor.debriefing_text.find(persona_index) != Traitor.debriefing_text.end())
				stagep->text = Traitor.debriefing_text[persona_index];
			else
				stagep->text = Traitor.debriefing_text[-1];

			// choose appropriate traitor voice for this mission
			debrief_choose_voice(stagep->voice, sizeof(stagep->voice), Traitor.traitor_voice_base, persona_index, 1);

			stagep->recommendation_text = Traitor.recommendation_text;
		}
	}

	if (!(Game_mode & GM_MULTIPLAYER) && (Game_mode & GM_CAMPAIGN_MODE)) {
		if (Campaign.next_mission == Campaign.current_mission){
			Must_replay_mission = 1;
		}
	}

	// disable the accept button if in single player and I am a traitor
	if (Turned_traitor || Must_replay_mission) {
		Buttons[gr_screen.res][ACCEPT_BUTTON].button.hide();

		// kill off any stats
		Player->flags &= ~PLAYER_FLAGS_PROMOTED;
		scoring_level_init( &Player->stats );
	}
}

// initialization for listing of players in game
void debrief_multi_list_init()
{
	Multi_list_size = 0;  // number of net players to choose from
	Multi_list_offset = 0;

	Multi_list_select = -1;

	if ( !(Game_mode & GM_MULTIPLAYER) ) 
		return;

	debrief_rebuild_player_list();

	// switch stats display to this newly selected player
	set_player_stats(Multi_list[0].net_player_index);
	strcpy_s(Debrief_current_callsign, Multi_list[0].callsign);	
	Debrief_player = Player;
}

void debrief_multi_list_scroll_up()
{
	// if we're at the beginning of the list, don't do anything
	if(Multi_list_offset == 0){
		gamesnd_play_iface(InterfaceSounds::GENERAL_FAIL);
		return;
	}

	// otherwise scroll up
	Multi_list_offset--;
	gamesnd_play_iface(InterfaceSounds::USER_SELECT);
}

void debrief_multi_list_scroll_down()
{		
	// if we can scroll down no further
	if(Multi_list_size < Debrief_multi_list_team_max_display[gr_screen.res]){
		gamesnd_play_iface(InterfaceSounds::GENERAL_FAIL);
		return;
	}
	if((Multi_list_offset + Debrief_multi_list_team_max_display[gr_screen.res]) >= Multi_list_size){
		gamesnd_play_iface(InterfaceSounds::GENERAL_FAIL);
		return;
	}

	// otherwise scroll down
	Multi_list_offset++;
	gamesnd_play_iface(InterfaceSounds::USER_SELECT);
}

// draw the connected net players
void debrief_multi_list_draw()
{
	int y, z, font_height,idx;
	char str[CALLSIGN_LEN+5];
	net_player *np;
	
	font_height = gr_get_font_height();	

	// if we currently have no item picked, pick a reasonable one
	if((Multi_list_size >= 0) && (Multi_list_select == -1)){
		// select the entry which corresponds to the local player
		Multi_list_select = 0;				
		for(idx=0;idx<Multi_list_size;idx++){
			if(Multi_list[idx].net_player_index == MY_NET_PLAYER_NUM){
				Multi_list_select = idx;

				// switch stats display to this newly selected player
				set_player_stats(Multi_list[idx].net_player_index);
				strcpy_s(Debrief_current_callsign, Multi_list[idx].callsign);	
				Debrief_player = Net_players[Multi_list[idx].net_player_index].m_player;				
				break;
			}
		}
	}

	// draw the list itself
	y = 0;
	z = Multi_list_offset;
	while (y + font_height <= Debrief_list_coords[gr_screen.res][3]){
		np = &Net_players[Multi_list[z].net_player_index];

		if (z >= Multi_list_size){
			break;
		}
		// set the proper text color for the highlight
		if(np->flags & NETINFO_FLAG_GAME_HOST){
			if(Multi_list_select == z){
				gr_set_color_fast(&Color_text_active_hi);
			} else {
				gr_set_color_fast(&Color_bright);
			}
		} else {
			if(Multi_list_select == z){
				gr_set_color_fast(&Color_text_active);
			} else {
				gr_set_color_fast(&Color_text_normal);
			}
		}

		// blit the proper indicator - skipping observers
		if(!((np->flags & NETINFO_FLAG_OBSERVER) && !(np->flags & NETINFO_FLAG_OBS_PLAYER))){
			if(Netgame.type_flags & NG_TYPE_TEAM){
				// team 0
				if(np->p_info.team == 0){
					// draw his "selected" icon
					if(((np->state == NETPLAYER_STATE_DEBRIEF_ACCEPT) || (np->state == NETPLAYER_STATE_DEBRIEF_REPLAY)) && (Multi_common_icons[MICON_TEAM0_SELECT] != -1)){
						gr_set_bitmap(Multi_common_icons[MICON_TEAM0_SELECT]);
						gr_bitmap(Debrief_list_coords[gr_screen.res][0], Debrief_list_coords[gr_screen.res][1] + y - 2, GR_RESIZE_MENU);
					} 
					// draw his "normal" icon
					else if(Multi_common_icons[MICON_TEAM0] != -1){
						gr_set_bitmap(Multi_common_icons[MICON_TEAM0]);
						gr_bitmap(Debrief_list_coords[gr_screen.res][0], Debrief_list_coords[gr_screen.res][1] + y - 2, GR_RESIZE_MENU);
					}					
				} else if(np->p_info.team == 1){
					// draw his "selected" icon
					if(((np->state == NETPLAYER_STATE_DEBRIEF_ACCEPT) || (np->state == NETPLAYER_STATE_DEBRIEF_REPLAY)) && (Multi_common_icons[MICON_TEAM1_SELECT] != -1)){						
						gr_set_bitmap(Multi_common_icons[MICON_TEAM1_SELECT]);
						gr_bitmap(Debrief_list_coords[gr_screen.res][0], Debrief_list_coords[gr_screen.res][1] + y - 2, GR_RESIZE_MENU);
					} 
					// draw his "normal" icon
					else if(Multi_common_icons[MICON_TEAM1] != -1){
						gr_set_bitmap(Multi_common_icons[MICON_TEAM1]);
						gr_bitmap(Debrief_list_coords[gr_screen.res][0], Debrief_list_coords[gr_screen.res][1] + y - 2, GR_RESIZE_MENU);
					}					
				}
			} else {
				// draw the team 0 selected icon
				if(((np->state == NETPLAYER_STATE_DEBRIEF_ACCEPT) || (np->state == NETPLAYER_STATE_DEBRIEF_REPLAY)) && (Multi_common_icons[MICON_TEAM0_SELECT] != -1)){
					gr_set_bitmap(Multi_common_icons[MICON_TEAM0_SELECT]);
					gr_bitmap(Debrief_list_coords[gr_screen.res][0], Debrief_list_coords[gr_screen.res][1] + y - 2, GR_RESIZE_MENU);
				}
			}
		}

		strcpy_s(str,Multi_list[z].callsign);
		if(Net_players[Multi_list[z].net_player_index].flags & NETINFO_FLAG_OBSERVER && !(Net_players[Multi_list[z].net_player_index].flags & NETINFO_FLAG_OBS_PLAYER)){
			strcat_s(str,XSTR( "(O)", 438));
		}		

		// bli
		gr_string(Debrief_list_coords[gr_screen.res][0] + MULTI_LIST_TEAM_OFFSET, Debrief_list_coords[gr_screen.res][1] + y, str, GR_RESIZE_MENU);

		y += font_height;
		z++;
	}
}

void debrief_kick_selected_player()
{
	if(Multi_list_select >= 0){
		Assert(Net_player->flags & NETINFO_FLAG_GAME_HOST);
		multi_kick_player(Multi_list[Multi_list_select].net_player_index);
	}
}


// get optional mission popup text 
void debrief_assemble_optional_mission_popup_text(char *buffer, char *mission_loop_desc)
{
	Assert(buffer != NULL);
	// base message

	if (mission_loop_desc == NULL) {
		strcpy(buffer, XSTR("<No Mission Loop Description Available>", 1490));
		mprintf(("No mission loop description available\n"));
	} else {
		strcpy(buffer, mission_loop_desc);
	}

	strcat(buffer, XSTR("\n\n\nDo you want to play the optional mission?", 1491));
}

bool debrief_can_accept()
{
	return !(/*Cheats_enabled ||*/ Turned_traitor || Must_replay_mission);
}

// what to do when the accept button is hit
void debrief_accept(int ok_to_post_start_game_event, bool API_Access)
{
	int go_loop = 0;

	//Skip this bit if we're in API mode because the API handles these popups differently
	if ( !debrief_can_accept() && (Game_mode & GM_CAMPAIGN_MODE) && !API_Access) {
		const char *str;
		int z;

		if (Game_mode & GM_MULTIPLAYER) {
			return;
		}

		if (Player_ship->team == Iff_traitor){
			str = XSTR( "Your career is over, Traitor!  You can't accept new missions!", 439);
		}/* else if (Cheats_enabled) {
			str = XSTR( "You are a cheater.  You cannot accept this mission!", 440);
		}*/ else {
			str = XSTR( "You have failed this mission and cannot accept.  What do you you wish to do instead?", 441);
		}

		z = popup(0, 3, XSTR( "Return to &Debriefing", 442), XSTR( "Go to &Flight Deck", 443), XSTR( "&Replay Mission", 444), str);
		if (z == 2){
			gameseq_post_event(GS_EVENT_START_GAME);  // restart mission
		} else if ( z == 1 ) {
			gameseq_post_event(GS_EVENT_END_GAME);  // return to main hall, tossing stats
		}

		return;
	}

	Debrief_accepted = 1;
	// save mission stats
	if (Game_mode & GM_MULTIPLAYER) {
		// note that multi_debrief_accept_hit() will handle all mission_campaign_* calls on its own
		// as well as doing stats transfers, etc.
		multi_debrief_accept_hit();
	} else {
		int play_commit_sound = 1;
		// only write the player's stats if he's accepted

		// if we are just playing a single mission, then don't do many of the things
		// that need to be done.  Nothing much should happen when just playing a single
		// mission that isn't in a campaign.
		if ( Game_mode & GM_CAMPAIGN_MODE ) {

			mission_campaign_store_variables(SEXP_VARIABLE_SAVE_ON_MISSION_PROGRESS);
			mission_campaign_store_containers(ContainerType::SAVE_ON_MISSION_PROGRESS);

			// check for possible mission loop
			// check for (1) mission loop available, (2) don't have to repeat last mission
			if(!(Game_mode & GM_MULTIPLAYER)){
				int cur = Campaign.current_mission;
				bool require_repeat_mission = (Campaign.current_mission == Campaign.next_mission);
				if (Campaign.missions[cur].flags & CMISSION_FLAG_HAS_LOOP) {
					Assert(Campaign.loop_mission != CAMPAIGN_LOOP_MISSION_UNINITIALIZED);
				}

				if ( (Campaign.missions[cur].flags & CMISSION_FLAG_HAS_LOOP) && (Campaign.loop_mission != -1) && !require_repeat_mission ) {
					/*
					char buffer[512];
					debrief_assemble_optional_mission_popup_text(buffer, Campaign.missions[cur].mission_loop_desc);

					int choice = popup(0 , 2, POPUP_NO, POPUP_YES, buffer);
					if (choice == 1) {
						Campaign.loop_enabled = 1;
						Campaign.next_mission = Campaign.loop_mission;
					}
					*/
					go_loop = 1;
				}
			}			

			// loopy loopy time
			if (go_loop && ok_to_post_start_game_event) {
				gameseq_post_event( GS_EVENT_LOOP_BRIEF );
			}
			// continue as normal
			else {
				// end the mission
				// if we can loop, but don't want to right now, then setup so that we can later
				mission_campaign_mission_over( (go_loop) ? false : true );

				// check to see if we are out of the loop now
				if ( Campaign.next_mission == Campaign.loop_reentry ) {
					Campaign.loop_enabled = 0;
				}

				// check if campaign is over, or if FREDer wants the mainhall
				if ( Campaign.next_mission == -1 || (The_mission.flags[Mission::Mission_Flags::End_to_mainhall]) ) {
					gameseq_post_event(GS_EVENT_MAIN_MENU);
				} else {
					if ( ok_to_post_start_game_event ) {
						gameseq_post_event(GS_EVENT_START_GAME);
					} else {
						play_commit_sound = 0;
					}
				}
			}
		} else {
			gameseq_post_event(GS_EVENT_MAIN_MENU);
		}

		// Goober5000
		if ( play_commit_sound && !(The_mission.flags[Mission::Mission_Flags::Toggle_debriefing])) {
			gamesnd_play_iface(InterfaceSounds::COMMIT_PRESSED);
		}

		game_flush();
	}
}

void debrief_next_tab()
{
	New_mode = Current_mode + 1;
	if (New_mode >= NUM_TABS)
		New_mode = 0;
}

void debrief_prev_tab()
{
	New_mode = Current_mode - 1;
	if (New_mode < 0)
		New_mode = NUM_TABS - 1;
}

// --------------------------------------------------------------------------------------
//	debrief_next_stage()
//
void debrief_next_stage()
{
	if (Current_stage < Num_stages - 1) {
		New_stage = Current_stage + 1;
		gamesnd_play_iface(InterfaceSounds::BRIEF_STAGE_CHG);

	} else
		gamesnd_play_iface(InterfaceSounds::BRIEF_STAGE_CHG_FAIL);
}

// --------------------------------------------------------------------------------------
//	debrief_prev_stage()
//
void debrief_prev_stage()
{
	if (Current_stage) {
		New_stage = Current_stage - 1;
		gamesnd_play_iface(InterfaceSounds::BRIEF_STAGE_CHG);

	} else
		gamesnd_play_iface(InterfaceSounds::BRIEF_STAGE_CHG_FAIL);
}

// --------------------------------------------------------------------------------------
//	debrief_first_stage()
void debrief_first_stage()
{
	if (Current_stage) {
		New_stage = 0;
		gamesnd_play_iface(InterfaceSounds::BRIEF_STAGE_CHG);

	} else
		gamesnd_play_iface(InterfaceSounds::BRIEF_STAGE_CHG_FAIL);
}

// --------------------------------------------------------------------------------------
//	debrief_last_stage()
void debrief_last_stage()
{
	if (Current_stage != Num_stages - 1) {
		New_stage = Num_stages - 1;
		gamesnd_play_iface(InterfaceSounds::BRIEF_STAGE_CHG);

	} else
		gamesnd_play_iface(InterfaceSounds::BRIEF_STAGE_CHG_FAIL);
}

// draw what stage number the debriefing is on
void debrief_render_stagenum()
{
	int w;
	char buf[64];
	
	if (Num_stages < 2)
		return;
		
	sprintf(buf, XSTR( "%d of %d", 445), Current_stage + 1, Num_stages);
	gr_get_string_size(&w, NULL, buf);
	gr_set_color_fast(&Color_bright_blue);
	gr_string(Debrief_stage_info_coords[gr_screen.res][0] - w, Debrief_stage_info_coords[gr_screen.res][1], buf, GR_RESIZE_MENU);
	gr_set_color_fast(&Color_white);
}

// render the mission difficulty at the specified y location
void debrief_render_mission_difficulty(int y_loc)
{	
	gr_string(0, y_loc, XSTR( "Skill Level", 1509), GR_RESIZE_MENU);
	gr_string(Debrief_text_x2[gr_screen.res], y_loc, Skill_level_names(Game_skill_level), GR_RESIZE_MENU);	
}

// render the mission time at the specified y location
void debrief_render_mission_time(int y_loc)
{
	char time_str[30];
	
	game_format_time(Missiontime, time_str);
	gr_string(0, y_loc, XSTR( "Mission Time", 446), GR_RESIZE_MENU);
	gr_string(Debrief_text_x2[gr_screen.res], y_loc, time_str, GR_RESIZE_MENU);	
}

// render out the stats info to the scroll window
//
void debrief_stats_render()
{	
	int i, y, font_height;	

	gr_set_color_fast(&Color_blue);
	gr_set_clip(Debrief_text_wnd_coords[gr_screen.res][0], Debrief_text_wnd_coords[gr_screen.res][1], Debrief_text_wnd_coords[gr_screen.res][2], Debrief_text_wnd_coords[gr_screen.res][3], GR_RESIZE_MENU);
	gr_string(0, 0, Debrief_current_callsign, GR_RESIZE_MENU);
	font_height = gr_get_font_height();
	y = 30;
	
	gr_set_color_fast(&Color_white);
	
	debrief_render_mission_difficulty(y);
	y += 2*font_height;
	
	switch ( Current_stage ) {
		case DEBRIEF_MISSION_STATS:
			i = Current_stage - 1;
			if ( i < 0 )
				i = 0;

			// display mission completion time
			debrief_render_mission_time(y);

			y += 2*font_height;
			show_stats_label(i, 0, y, font_height);
			show_stats_numbers(i, Debrief_text_x2[gr_screen.res], y, font_height);
			break;
		case DEBRIEF_ALLTIME_STATS:
			i = Current_stage - 1;
			if ( i < 0 )
				i = 0;

			show_stats_label(i, 0, y, font_height);
			show_stats_numbers(i, Debrief_text_x2[gr_screen.res], y, font_height);
			break;

		case DEBRIEF_ALLTIME_KILLS:
		case DEBRIEF_MISSION_KILLS:
			i = Text_offset;
			while (y + font_height <= Debrief_text_wnd_coords[gr_screen.res][3]) {
				if (i >= Num_text_lines)
					break;

				if (!i) {
					if ( Current_stage == DEBRIEF_MISSION_KILLS )
						gr_printf_menu(0, y, "%s", XSTR( "Mission Kills by Ship Type", 447));
					else
						gr_printf_menu(0, y, "%s", XSTR( "All-time Kills by Ship Type", 448));

				} else if (i > 1) {
					//Assert: Was debrief_setup_ship_kill_stats called?
					Assert(Debrief_stats_kills != NULL);

					gr_printf_menu(0, y, "%s", Debrief_stats_kills[i - 2].text);
					gr_printf_menu(Debrief_text_x2[gr_screen.res], y, "%d", Debrief_stats_kills[i - 2].num);
				}

				y += font_height;
				i++;
			}

			if (Num_text_lines == 2) {
				if ( Current_stage == DEBRIEF_MISSION_KILLS )
					gr_printf_menu(0, y, "%s", XSTR( "(No ship kills this mission)", 449));
				else
					gr_printf_menu(0, y, "%s", XSTR( "(No ship kills)", 450));
			}

			break;

		default:
			Int3();
			break;
	} 

	gr_reset_clip();
}

// do action for when the replay button is pressed
void debrief_replay_pressed()
{	
	if (!Turned_traitor && !Must_replay_mission && (Game_mode & GM_CAMPAIGN_MODE)) {
		int choice;
		choice = popup(0, 2, POPUP_CANCEL, XSTR( "&Replay", 451), XSTR( "If you choose to replay this mission, you will be required to complete it again before proceeding to future missions.\n\nIn addition, any statistics gathered during this mission will be discarded if you choose to replay.", 452));

		if (choice != 1){
			return;
		}
	}

	gameseq_post_event(GS_EVENT_START_GAME);	// restart mission
	gamesnd_play_iface(InterfaceSounds::COMMIT_PRESSED);
}

// -------------------------------------------------------------------
// debrief_redraw_pressed_buttons()
//
// Redraw any debriefing buttons that are pressed down.  This function is needed
// since we sometimes need to draw pressed buttons last to ensure the entire
// button gets drawn (and not overlapped by other buttons)
//
void debrief_redraw_pressed_buttons()
{
	int i;
	UI_BUTTON *b;
	
	for ( i=0; i<NUM_BUTTONS; i++ ) {
		b = &Buttons[gr_screen.res][i].button;
		// don't draw the recommendations button if we're in stats mode
		if ( b->button_down() ) {
			b->draw_forced(2);
		}
	}
}

// debrief specific button with hotspot 'i' has been pressed, so perform the associated action
//
void debrief_button_pressed(int num)
{
	switch (num) {
		case DEBRIEF_TAB:
			Buttons[gr_screen.res][RECOMMENDATIONS].button.enable();			
			// Debrief_ui_window.use_hack_to_get_around_stupid_problem_flag = 0;
			if (num != Current_mode){
				gamesnd_play_iface(InterfaceSounds::SCREEN_MODE_PRESSED);
			}
			New_mode = num;
			break;
		case STATS_TAB:
			// Debrief_ui_window.use_hack_to_get_around_stupid_problem_flag = 1;			// allows failure sound to be played
			Buttons[gr_screen.res][RECOMMENDATIONS].button.disable();			
			if (num != Current_mode){
				gamesnd_play_iface(InterfaceSounds::SCREEN_MODE_PRESSED);
			}
			New_mode = num;
			break;

		case TEXT_SCROLL_UP:
			if (Text_offset) {
				Text_offset--;
				gamesnd_play_iface(InterfaceSounds::SCROLL);
			} else {
				gamesnd_play_iface(InterfaceSounds::GENERAL_FAIL);
			}
			break;

		case TEXT_SCROLL_DOWN:
			if (Max_debrief_Lines < (Num_text_lines - Text_offset)) {
				Text_offset++;
				gamesnd_play_iface(InterfaceSounds::SCROLL);
			} else {
				gamesnd_play_iface(InterfaceSounds::GENERAL_FAIL);
			}
			break;

		case REPLAY_MISSION:
			if(Game_mode & GM_MULTIPLAYER){
				multi_debrief_replay_hit();
			} else {			
				debrief_replay_pressed();	
			}
			break;

		case RECOMMENDATIONS:
			gamesnd_play_iface(InterfaceSounds::USER_SELECT);
			Recommend_active = !Recommend_active;
			debrief_text_init();
			break;

		case FIRST_STAGE:
			debrief_first_stage();
			break;

		case PREV_STAGE:
			debrief_prev_stage();
			break;

		case NEXT_STAGE:
			debrief_next_stage();
			break;

		case LAST_STAGE:
			debrief_last_stage();
			break;

		case HELP_BUTTON:
			gamesnd_play_iface(InterfaceSounds::HELP_PRESSED);
			launch_context_help();
			break;

		case OPTIONS_BUTTON:
			gamesnd_play_iface(InterfaceSounds::SWITCH_SCREENS);
			gameseq_post_event( GS_EVENT_OPTIONS_MENU );
			break;

		case ACCEPT_BUTTON:
			debrief_accept();
			break;

		case MEDALS_BUTTON:
			gamesnd_play_iface(InterfaceSounds::SWITCH_SCREENS);
			gameseq_post_event(GS_EVENT_VIEW_MEDALS);
			break;

		case PLAYER_SCROLL_UP:
			debrief_multi_list_scroll_up();
			break;

		case PLAYER_SCROLL_DOWN:
			debrief_multi_list_scroll_down();
			break;

		case MULTI_PINFO_POPUP:
			Debrief_should_show_popup = 1;
			break;

		case MULTI_KICK:
			debrief_kick_selected_player();
			break;
	} // end swtich
}

void debrief_setup_ship_kill_stats(int  /*stage_num*/)
{
	int i;
	//ushort *kill_arr;
	int *kill_arr;	//DTP max ships
	debrief_stats_kill_info	*kill_info;

	Assert(Current_stage < DEBRIEF_NUM_STATS_PAGES);
	if ( Current_stage == DEBRIEF_MISSION_STATS || Current_stage == DEBRIEF_ALLTIME_STATS )
		return;

	if(Debrief_stats_kills == NULL)
	{
		Debrief_stats_kills = new debrief_stats_kill_info[Ship_info.size()];
	}

	Assert(Debrief_player != NULL);

	// kill_ar points to an array of MAX_SHIP_TYPE ints
	if ( Current_stage == DEBRIEF_MISSION_KILLS ) {
		kill_arr = Debrief_player->stats.m_okKills;
	} else {		
		kill_arr = Debrief_player->stats.kills;
	}

	Num_text_lines = 0;
	i = 0;
	for ( auto it = Ship_info.begin(); it != Ship_info.end(); i++, ++it ) {

		// code used to add in mission kills, but the new system assumes that the player will accept, so
		// all time stats already have mission stats added in.
		if ( kill_arr[i] <= 0 ){
			continue;
		}


		kill_info = &Debrief_stats_kills[Num_text_lines++];

		kill_info->num = kill_arr[i];

		strcpy_s(kill_info->text, it->name);
		strcat_s(kill_info->text, NOX(":"));
	}

	Num_text_lines += 2;
}

// Iterate through the debriefing buttons, checking if they are pressed
void debrief_check_buttons()
{
	int i;

	for ( i=0; i<NUM_BUTTONS; i++ ) {
		if ( Buttons[gr_screen.res][i].button.pressed() ) {
			debrief_button_pressed(i);
		}
	}

	int y, z;

	if ( !(Game_mode & GM_MULTIPLAYER) ) 
		return;

	if (List_region.pressed()) {
		List_region.get_mouse_pos(NULL, &y);
		z = Multi_list_offset + y / gr_get_font_height();
		if ((z >= 0) && (z < Multi_list_size)) {
			// switch stats display to this newly selected player
			set_player_stats(Multi_list[z].net_player_index);
			strcpy_s(Debrief_current_callsign, Multi_list[z].callsign);
			Debrief_player = Net_players[Multi_list[z].net_player_index].m_player;
			Multi_list_select = z;
			debrief_setup_ship_kill_stats(Current_stage);
			gamesnd_play_iface(InterfaceSounds::USER_SELECT);
		}
	}	

	// if the player was double clicked on - we should popup a player info popup
	/*
	if (List_region.double_clicked()) {
		Debrief_should_show_popup = 1;
	}
	*/
}

// setup the debriefing text lines for rendering
void debrief_text_init()
{
	int r_count = 0;
	const char *src;
	int i;

	// If no wav files are being used use speech simulation
	bool use_sim_speech = true;
	for (i = 0; i < MAX_DEBRIEF_STAGES; i++) {
		if(Debrief_voices[i] != -1) {
		 	use_sim_speech = false;
			break;
		}
	}

	// Make sure that the text wrapping and the rendering code use the same font
	font::set_font(DEBRIEFING_FONT);

	Num_text_lines = Text_offset = brief_color_text_init("", Debrief_text_wnd_coords[gr_screen.res][2], default_debriefing_color, 0, 0);	// Initialize color stuff -MageKing17

	fsspeech_start_buffer();

	if (Current_mode == DEBRIEF_TAB) {
		for (i=0; i<Num_debrief_stages; i++) {
			if (i)
				// add a blank line between stages
				Num_text_lines += brief_color_text_init("\n", Debrief_text_wnd_coords[gr_screen.res][2], default_debriefing_color, 0, MAX_DEBRIEF_LINES, true);

			src = Debrief_stages[i]->text.c_str();

			if (*src) {
				Num_text_lines += brief_color_text_init(src, Debrief_text_wnd_coords[gr_screen.res][2], default_debriefing_color, 0, MAX_DEBRIEF_LINES, true);

				if (use_sim_speech && !Recommend_active) {
					fsspeech_stuff_buffer(src);
					fsspeech_stuff_buffer("\n");
				}
			}

			if (Recommend_active) {
				src = Debrief_stages[i]->recommendation_text.c_str();

				if ((i == Num_debrief_stages - 1) && !r_count && !*src)
					src = XSTR( "We have no recommendations for you.", 1054);

				if (*src) {
					Num_text_lines += brief_color_text_init("\n", Debrief_text_wnd_coords[gr_screen.res][2], default_recommendation_color, 0, MAX_DEBRIEF_LINES, true);

					Num_text_lines += brief_color_text_init(src, Debrief_text_wnd_coords[gr_screen.res][2], default_recommendation_color, 0, MAX_DEBRIEF_LINES, true);
					r_count++;

					if (use_sim_speech) {
						fsspeech_stuff_buffer(src);
						fsspeech_stuff_buffer("\n");
					}
				}
			}
		}
		Brief_text_wipe_time_elapsed = BRIEF_TEXT_WIPE_TIME;	// Skip the wipe effect

		if(use_sim_speech) {
			fsspeech_play_buffer(FSSPEECH_FROM_BRIEFING);
		}
		return;
	}

	// not in debriefing mode, must be in stats mode
	Num_text_lines = 0;
	debrief_setup_ship_kill_stats(Current_stage);
}

//Move this into its own method to allow easier API access - Mjn
int debrief_select_music()
{

	if (Turned_traitor || ((Game_mode & GM_CAMPAIGN_MODE) && (Campaign.next_mission == Campaign.current_mission))) {
		// you failed the mission, so you get the fail music
		return SCORE_DEBRIEFING_FAILURE;
	} else if (mission_goals_met()) {
		// you completed all primaries and secondaries, so you get the win music
		return SCORE_DEBRIEFING_SUCCESS;
	} else {
		// you somehow passed the mission, so you get a little something for your efforts.
		return SCORE_DEBRIEFING_AVERAGE;
	}

}


// --------------------------------------------------------------------------------------
//

// start up the appropriate music
static void debrief_init_music()
{
	
	Debrief_music_timeout = UI_TIMESTAMP::invalid();

	int score = debrief_select_music();

	// if multi client then give a slight delay before playing average music
	// since we'd like to eval the goals once more for slow clients
	if ( MULTIPLAYER_CLIENT && (score == SCORE_DEBRIEFING_AVERAGE) ) {
		Debrief_music_timeout = ui_timestamp(2000);
		return;
	}

	common_music_init(score);
}

void debrief_init(bool API_Access)
{
	Assert(!Debrief_inited);
//	Campaign.loop_enabled = 0;
	Campaign.loop_mission = CAMPAIGN_LOOP_MISSION_UNINITIALIZED;

	// MageKing17 - Set the font so that wordwrapping in brief_color_text_init() calculates based on the same font as the debriefing itself.
	font::set_font(DEBRIEFING_FONT);

	// set up the right briefing for this guy
	if(MULTI_TEAM){
		Debriefing = &Debriefings[Net_player->p_info.team];
	} else {
		Debriefing = &Debriefings[0];			
	}

	// no longer is mission
	Game_mode &= ~(GM_IN_MISSION);	

	game_flush();
	Current_mode = -1;
	New_mode = DEBRIEF_TAB;
	Recommend_active = Award_active = 0;

	Current_stage = -1;
	New_stage = 0;
	Debrief_cue_voice = UI_TIMESTAMP::invalid();
	Num_text_lines = 0;
	Debrief_first_voice_flag = 1;

	Debrief_multi_voice_loaded = 0;

	if ( (Game_mode & GM_CAMPAIGN_MODE) && ( !MULTIPLAYER_CLIENT )	) {
		// MUST store goals and events first - may be used to evaluate next mission
		// store goals and events
		mission_campaign_store_goals_and_events();

		// evaluate next mission
		mission_campaign_eval_next_mission();
	}

	// call traitor init before calling scoring_level_close.  traitor init will essentially nullify
	// any stats
	if ( !(Game_mode & GM_MULTIPLAYER) ) {	// only do for single player
		debrief_traitor_init();					// initialize data needed if player becomes traitor.
	}

	// call scoring level close for my stats.  Needed for award_init.  The stats will
	// be backed out if used chooses to replace them.
	scoring_level_close();

	if (!API_Access) {
		debrief_ui_init(); // init UI items
	}
	debrief_award_init();
	show_stats_init();
	debrief_voice_init();

	debrief_multi_list_init();

//	rank_bitmaps_clear();
//	rank_bitmaps_load();

	strcpy_s(Debrief_current_callsign, Player->callsign);
	Debrief_player = Player;
//	Debrief_current_net_player_index = debrief_multi_list[0].net_player_index;

	// Only setup Debrief_stages and Recommendations if not running through API access.
	if (!API_Access) {
		// set up the Debrief_stages[] and Recommendations[] arrays.  Only do the following stuff
		// for non-clients (i.e. single and game server).  Multiplayer clients will get their debriefing
		// info directly from the server.
		if (!MULTIPLAYER_CLIENT) {
			debrief_set_stages_and_multi_stuff();

			if (Num_debrief_stages <= 0) {
				Num_debrief_stages = 0;
			} else if (!API_Access) { // Do not load voice files in API mode -Mjn
				debrief_voice_load_all();
			}
		} else {
			// multiplayer client may have already received their debriefing info.  If they have not,
			// then set the num debrief stages to 0
			if (!Debrief_multi_stages_loaded) {
				Num_debrief_stages = 0;
			}
		}
	}

	/*
	if (mission_evaluate_primary_goals() == PRIMARY_GOALS_COMPLETE) {
		common_music_init(SCORE_DEBRIEFING_SUCCESS);
	} else {
		common_music_init(SCORE_DEBRIEFING_FAILURE);
	}
	*/

	// Just calculate this once instead of every frame. -MageKing17
	Max_debrief_Lines = Debrief_text_wnd_coords[gr_screen.res][3]/gr_get_font_height(); //Make the max number of lines dependent on the font height.

	// start up the appropriate music only if we're not in API mode - Mjn
	if (!API_Access) {
		debrief_init_music();
	}

	if ((Game_mode & GM_CAMPAIGN_MODE) && (Campaign.next_mission == Campaign.current_mission)) {
		// Better luck next time; increase retries.
		Player->failures_this_session++;
	} else {
		// Clear retry count regardless of whether or not the player accepts.
		Player->failures_this_session = 0;
	}

	if (Game_mode & GM_MULTIPLAYER) {
		multi_debrief_init();

		// if i'm not the host of the game, disable the multi kick button
		if (!API_Access && !(Net_player->flags & NETINFO_FLAG_GAME_HOST)) {
			Buttons[gr_screen.res][MULTI_KICK].button.disable();
		}
	} else {
		if (!API_Access) {
			Buttons[gr_screen.res][PLAYER_SCROLL_UP].button.disable();
			Buttons[gr_screen.res][PLAYER_SCROLL_DOWN].button.disable();
			Buttons[gr_screen.res][MULTI_PINFO_POPUP].button.disable();
			Buttons[gr_screen.res][MULTI_KICK].button.disable();
			Buttons[gr_screen.res][PLAYER_SCROLL_UP].button.hide();
			Buttons[gr_screen.res][PLAYER_SCROLL_DOWN].button.hide();
			Buttons[gr_screen.res][MULTI_PINFO_POPUP].button.hide();
			Buttons[gr_screen.res][MULTI_KICK].button.hide();
		}
	}

	if (!API_Access && !Award_active) {
		Buttons[gr_screen.res][MEDALS_BUTTON].button.disable();
		Buttons[gr_screen.res][MEDALS_BUTTON].button.hide();
	}

	Debrief_skip_popup_already_shown = 0;

	Debrief_inited = 1;
}

// --------------------------------------------------------------------------------------
//	debrief_close()
void debrief_close(bool API_Access)
{
	int i;
	scoring_struct *sc;

	Assert(Debrief_inited);

	// if the mission wasn't accepted, clear out my stats
	// we need to evaluate a little differently for multiplayer since the conditions for "accepting" 
	// are a little bit different
	if (Game_mode & GM_MULTIPLAYER) {
		// if stats weren't accepted, backout my own stats
		if (multi_debrief_stats_accept_code() != 1) {
			if(MULTIPLAYER_MASTER){
				for(i=0; i<MAX_PLAYERS; i++){
					if(MULTI_CONNECTED(Net_players[i]) && !MULTI_STANDALONE(Net_players[i]) && !MULTI_PERM_OBSERVER(Net_players[i]) && (Net_players[i].m_player != NULL)){
						sc = &Net_players[i].m_player->stats;
						scoring_backout_accept(sc);

						if (Net_player == &Net_players[i]) {
							Pilot.update_stats_backout( sc, (The_mission.game_type == MISSION_TYPE_TRAINING) );
						}
					}
				}
			} else {
				scoring_backout_accept( &Player->stats );
				Pilot.update_stats_backout( &Player->stats, (The_mission.game_type == MISSION_TYPE_TRAINING) );
			}
		}
	} else {
		// single player
		if( !Debrief_accepted || !(Game_mode & GM_CAMPAIGN_MODE) ){
			// Make sure we don't skip any missions in a campaign.
			if ( Game_mode & GM_CAMPAIGN_MODE ) {
				Campaign.next_mission = Campaign.current_mission;
			}
			scoring_backout_accept( &Player->stats );
			Pilot.update_stats_backout( &Player->stats, (The_mission.game_type == MISSION_TYPE_TRAINING) );
		}
	}

	// if dude passed the misson and accepted, reset his show skip popup flag
	if (Debrief_accepted) {
		Player->show_skip_popup = 1;
	}

	// clear out debrief info parsed from mission file - taylor
	mission_debrief_common_reset();

	// clear out award text 
	Debrief_award_text_num_lines = 0;

	//These don't need to be handled when accessing through the API -Mjn
	if (!API_Access) {
		debrief_voice_unload_all();
		common_music_close();
		chatbox_close();
	}

	// unload bitmaps
	// Not used by the API
	if (!API_Access && Background_bitmap >= 0) {
		bm_release(Background_bitmap);
	}

	// Not used by the API
	if (!API_Access && Award_bg_bitmap >= 0) {
		bm_release(Award_bg_bitmap);
	}

	if (Rank_bitmap >= 0){
		bm_release(Rank_bitmap);
	}

	if (Medal_bitmap >= 0){
		bm_release(Medal_bitmap);
	}

	if (Badge_bitmap >= 0){
		bm_release(Badge_bitmap);
	}

	if (!API_Access) {
		Debrief_ui_window.destroy();
		common_free_interface_palette(); // restore game palette
	}
	show_stats_close();

	if (Game_mode & GM_MULTIPLAYER){
		multi_debrief_close();
	}

	if(Debrief_stats_kills != NULL)
	{
		delete[] Debrief_stats_kills;
		Debrief_stats_kills = NULL;
	}
	game_flush();

	Stage_voice = -1;

	Debriefing_paused = 0;

	Debrief_inited = 0;
}

// handle keypresses in debriefing
void debrief_do_keys(int new_k)
{
	switch (new_k) {
		case KEY_TAB:
			debrief_next_tab();
			break;

		case KEY_SHIFTED | KEY_TAB:
			debrief_prev_tab();
			break;

		case KEY_ESC: {
			int pf_flags;
			int choice;

			// multiplayer accept popup is a little bit different
			if (Game_mode & GM_MULTIPLAYER) {		
				multi_debrief_esc_hit();
			} else {
				// display the normal debrief popup
				if (!Turned_traitor && !Must_replay_mission && (Game_mode & GM_CAMPAIGN_MODE)) {
					pf_flags = PF_BODY_BIG; // | PF_USE_AFFIRMATIVE_ICON | PF_USE_NEGATIVE_ICON;
					choice = popup(pf_flags, 3, POPUP_CANCEL, XSTR( "&Yes", 454), XSTR( "&No, retry later", 455), XSTR( "Accept this mission outcome?", 456));
					if (choice == 1) {  // accept and continue on
						debrief_accept(0);
						gameseq_post_event(GS_EVENT_MAIN_MENU);
					}

					if (choice < 1)
						break;

				} else if ( ( Turned_traitor || Must_replay_mission ) && (Game_mode & GM_CAMPAIGN_MODE)) {
					// need to popup saying that mission was a failure and must be replayed
					choice = popup(0, 2, POPUP_NO, POPUP_YES, XSTR( "Because this mission was a failure, you must replay this mission when you continue your campaign.\n\nReturn to the Flight Deck?", 457));
					if (choice <= 0) {
						break;
					}
				}

				// Return to Main Hall
				gameseq_post_event(GS_EVENT_END_GAME);
			}
		}

		default:
			break;
	}	// end switch
}

// uuuuuugly
void debrief_draw_award_text()
{
	int start_y, curr_y, i, x, sw;
	int fh = gr_get_font_height();
	int field_width = (Medal_bitmap > 0) ? Debrief_award_text_width[gr_screen.res][DB_WITH_MEDAL] : Debrief_award_text_width[gr_screen.res][DB_WITHOUT_MEDAL];

	// vertically centered within field
	start_y = Debrief_award_text_coords[gr_screen.res][1] + ((Debrief_award_text_coords[gr_screen.res][2] - (fh * Debrief_award_text_num_lines)) / 2);
	curr_y = start_y;

	// draw the strings
	for (i=0; i<Debrief_award_text_num_lines; i++) {
		gr_get_string_size(&sw, NULL, Debrief_award_text[i]);
		x = (Medal_bitmap < 0) ? (Debrief_award_text_coords[gr_screen.res][0] + (field_width - sw) / 2) : Debrief_award_text_coords[gr_screen.res][0];
		if (i==AWARD_TEXT_MAX_LINES-1) x += 7;				// hack because of the shape of the box
		gr_set_color_fast(&Color_white);
		gr_string(x, curr_y, Debrief_award_text[i], GR_RESIZE_MENU);

		// adjust y pos, including a little extra between the "pairs"
		curr_y += fh;
		if ((i == 1) || (i == 3)) { 
			curr_y += ((gr_screen.res == GR_640) ? 2 : 6);
		}
	}
}

// clears out text array so we don't have old award text showing up on new awards.
void debrief_award_text_clear() {
	int i;
	
	Debrief_award_text_num_lines = 0;
	for (i=0; i<AWARD_TEXT_MAX_LINES; i++) {
		//Debrief_award_text[i][0] = 0;
		memset(Debrief_award_text[i], 0, sizeof(char)*AWARD_TEXT_MAX_LINE_LENGTH);
	}
}

// this is the nastiest code I have ever written.  if you are modifying this, i feel bad for you.
void debrief_add_award_text(const char *str)
{
	Assert(Debrief_award_text_num_lines < AWARD_TEXT_MAX_LINES);
	if (Debrief_award_text_num_lines >= AWARD_TEXT_MAX_LINES) {
		return;
	}

	char *line2;
	int field_width = (Medal_bitmap > 0) ? Debrief_award_text_width[gr_screen.res][DB_WITH_MEDAL] : Debrief_award_text_width[gr_screen.res][DB_WITHOUT_MEDAL];

	// copy in the line
	strcpy_s(Debrief_award_text[Debrief_award_text_num_lines], str);	

	if (!Disable_built_in_translations) {
		// maybe translate for displaying
		if (Lcl_gr) {
			lcl_translate_medal_name_gr(Debrief_award_text[Debrief_award_text_num_lines]);
		} else if (Lcl_pl) {
			lcl_translate_medal_name_pl(Debrief_award_text[Debrief_award_text_num_lines]);
		}
	}

	Debrief_award_text_num_lines++;

	// if its too long, split once ONLY
	// assumes text isnt > 2 lines, but this is a safe assumption due to the char limits of the ranks/badges/etc
	if (Debrief_award_text_num_lines < AWARD_TEXT_MAX_LINES) {
		line2 = split_str_once(Debrief_award_text[Debrief_award_text_num_lines-1], field_width);
		if (line2 != NULL) {
			sprintf(Debrief_award_text[Debrief_award_text_num_lines], " %s", line2);  // indent a space
		}
		Debrief_award_text_num_lines++;		// leave blank line even if it all fits into 1
	}
}

//	called once per frame to drive all the input reading and rendering
void debrief_do_frame(float frametime)
{
	int k=0, new_k=0;
	const char *please_wait_str = XSTR("Please Wait", 1242);
	char buf[256];

	Assert(Debrief_inited);	

	// Goober5000 - accept immediately if skipping debriefing
	if (The_mission.flags[Mission::Mission_Flags::Toggle_debriefing])
	{
		// make sure that we can actually advance - we don't want an endless loop!!!
		if ( !((/*Cheats_enabled ||*/ Turned_traitor || Must_replay_mission) && (Game_mode & GM_CAMPAIGN_MODE)) )
		{
			debrief_accept();
			return;
		}
	}

	int str_w, str_h;

	// first thing is to load the files
	if ( MULTIPLAYER_CLIENT && !Debrief_multi_stages_loaded ) {
		// draw the background, etc
		GR_MAYBE_CLEAR_RES(Background_bitmap);
		if (Background_bitmap >= 0) {
			gr_set_bitmap(Background_bitmap);
			gr_bitmap(0, 0, GR_RESIZE_MENU);
		}

		Debrief_ui_window.draw();
		chatbox_render();
		if ( Debrief_multi_loading_bitmap > -1 ){
			gr_set_bitmap(Debrief_multi_loading_bitmap);		
			gr_bitmap( Please_wait_coords[gr_screen.res][0], Please_wait_coords[gr_screen.res][1], GR_RESIZE_MENU );
		}

		// draw "Please Wait"		
		gr_set_color_fast(&Color_normal);
		font::set_font(font::FONT2);
		gr_get_string_size(&str_w, &str_h, please_wait_str);
		gr_string((gr_screen.max_w_unscaled - str_w) / 2, (gr_screen.max_h_unscaled - str_h) / 2, please_wait_str, GR_RESIZE_MENU);
		font::set_font(font::FONT1);

		gr_flip();

		// make sure we run the debrief do frame
		if (Game_mode & GM_MULTIPLAYER) {
			multi_debrief_do_frame();
		}

		// esc pressed?		
		os_poll();	
		int keypress = game_check_key();	
		if(keypress == KEY_ESC){
			// popup to leave
			multi_quit_game(PROMPT_CLIENT);
		}

		return;
	}

	// if multiplayer client, and not loaded voice, then load it
	if ( MULTIPLAYER_CLIENT && !Debrief_multi_voice_loaded ) {
		debrief_multi_fixup_stages();
		debrief_voice_load_all();
		Debrief_multi_voice_loaded = 1;
	}

	if ( help_overlay_active(Debrief_overlay_id) ) {
		Buttons[gr_screen.res][HELP_BUTTON].button.reset_status();
		Debrief_ui_window.set_ignore_gadgets(1);
	}


	k = chatbox_process();

	if ( Game_mode & GM_NORMAL ) {
		new_k = Debrief_ui_window.process(k);
	} else {
		new_k = Debrief_ui_window.process(k, 0);
	}

	if ( (k > 0) || (new_k > 0) || B1_JUST_RELEASED ) {
		if ( help_overlay_active(Debrief_overlay_id) ) {
			help_overlay_set_state(Debrief_overlay_id, gr_screen.res, 0);
			Debrief_ui_window.set_ignore_gadgets(0);
			k = 0;
			new_k = 0;
		}
	}

	if ( !help_overlay_active(Debrief_overlay_id) ) {
		Debrief_ui_window.set_ignore_gadgets(0);
	}

	// don't show pilot info popup by default
	Debrief_should_show_popup = 0;

	// see if the mode has changed and handle it if so.
	if ( Current_mode != New_mode ) {
		debrief_voice_stop();
		Current_mode = New_mode;
		Current_stage = -1;
		New_stage = 0;
		if (New_mode == DEBRIEF_TAB) {
			Num_stages = 1;
			Debrief_cue_voice = UI_TIMESTAMP::invalid();
			Stage_voice = -1;
			if (Debrief_first_voice_flag) {
				Debrief_cue_voice = ui_timestamp(DEBRIEF_VOICE_DELAY * 3);
				Debrief_first_voice_flag = 0;
			}
		} else {
			Num_stages = DEBRIEF_NUM_STATS_PAGES;
		}
	}

	if ((Num_stages > 0) &&  (New_stage != Current_stage)) {
		Current_stage = New_stage;
		debrief_text_init();
	}

	debrief_voice_play();

	// multi clients get a slight delay before music start to check goals again
	if ( Debrief_music_timeout.isValid() ) {
		if ( ui_timestamp_elapsed(Debrief_music_timeout) ) {
			Debrief_music_timeout = UI_TIMESTAMP::invalid();

			if ( mission_goals_met() ) {
				common_music_init(SCORE_DEBRIEFING_SUCCESS);
			} else {
				common_music_init(SCORE_DEBRIEFING_AVERAGE);
			}

			common_music_do();
		}
	} else {	
		common_music_do();
	}

	if (Game_mode & GM_MULTIPLAYER) {
		multi_debrief_do_frame();
	}

	// Now do all the rendering for the frame
	GR_MAYBE_CLEAR_RES(Background_bitmap);
	if (Background_bitmap >= 0) {
		gr_set_bitmap(Background_bitmap);
		gr_bitmap(0, 0, GR_RESIZE_MENU);
	} 

	// draw the awarded stuff, G
	if ( Award_active && (Award_bg_bitmap >= 0) ) {
		gr_set_bitmap(Award_bg_bitmap);
		gr_bitmap(Debrief_award_wnd_coords[gr_screen.res][0], Debrief_award_wnd_coords[gr_screen.res][1], GR_RESIZE_MENU);
		if (Rank_bitmap >= 0) {
			gr_set_bitmap(Rank_bitmap);
			gr_bitmap(Debrief_award_coords[gr_screen.res][0], Debrief_award_coords[gr_screen.res][1], GR_RESIZE_MENU);
		}

		if (Medal_bitmap >= 0) {
			gr_set_bitmap(Medal_bitmap);
			gr_bitmap(Debrief_award_coords[gr_screen.res][0], Debrief_award_coords[gr_screen.res][1], GR_RESIZE_MENU);
		}

		if (Badge_bitmap >= 0) {
			gr_set_bitmap(Badge_bitmap);
			gr_bitmap(Debrief_award_coords[gr_screen.res][0], Debrief_award_coords[gr_screen.res][1], GR_RESIZE_MENU);
		}

		//  draw medal/badge/rank labels
		debrief_draw_award_text();
	}
	
	Debrief_ui_window.draw();
	debrief_redraw_pressed_buttons();
	Buttons[gr_screen.res][Current_mode].button.draw_forced(2);
	if (Recommend_active && (Current_mode != STATS_TAB)) {
		Buttons[gr_screen.res][RECOMMENDATIONS].button.draw_forced(2);
	}

	// draw the title of the mission
	gr_set_color_fast(&Color_bright_white);
	strcpy_s(buf, The_mission.name);
	font::force_fit_string(buf, 255, Debrief_title_coords[gr_screen.res][2]);
	gr_string(Debrief_title_coords[gr_screen.res][0], Debrief_title_coords[gr_screen.res][1], buf, GR_RESIZE_MENU);	

#if !defined(NDEBUG)
	gr_set_color_fast(&Color_normal);
	gr_printf_menu(Debrief_title_coords[gr_screen.res][0], Debrief_title_coords[gr_screen.res][1] - 10, NOX("[name: %s, mod: %s]"), Mission_filename, The_mission.modified);
#endif

	// Set the font for the debriefing instead of relying on the implicit font-setting of Debrief_ui_window.draw() -MageKing17
	font::set_font(DEBRIEFING_FONT);

	// draw the screen-specific text
	switch (Current_mode) {
		case DEBRIEF_TAB:
			if ( Num_debrief_stages <= 0 ) {
				gr_set_color_fast(&Color_white);
				Assert( Game_current_mission_filename != NULL );
				gr_printf_menu(Debrief_text_wnd_coords[gr_screen.res][0], Debrief_text_wnd_coords[gr_screen.res][1], XSTR( "No Debriefing for mission: %s", 458), Game_current_mission_filename);

			} else {
				brief_render_text(Text_offset, Debrief_text_wnd_coords[gr_screen.res][0], Debrief_text_wnd_coords[gr_screen.res][1], Debrief_text_wnd_coords[gr_screen.res][3], frametime);
			}

			break;

		case STATS_TAB:
			debrief_stats_render();
			break;
	} // end switch

	if ( (Max_debrief_Lines + Text_offset) < Num_text_lines ) {
		int w;

		gr_set_color_fast(&Color_more_indicator);
		gr_get_string_size(&w, NULL, XSTR( "More", 459));
		gr_printf_menu(Debrief_text_wnd_coords[gr_screen.res][0] + Debrief_text_wnd_coords[gr_screen.res][2] / 2 - w / 2, Debrief_text_wnd_coords[gr_screen.res][1] + Debrief_text_wnd_coords[gr_screen.res][3], "%s", XSTR( "More", 459));
	}

	debrief_render_stagenum();
	debrief_multi_list_draw();

	// render some extra stuff in multiplayer
	if (Game_mode & GM_MULTIPLAYER) {
		// render the chatbox last
		chatbox_render();

		// draw tooltips
		Debrief_ui_window.draw_tooltip();

		// render the status indicator for the voice system
		multi_common_voice_display_status();
	}

	// AL 3-6-98: Needed to move key reading here, since popups are launched from this code, and we don't
	//				  want to include the mouse pointer which is drawn in the flip

	if ( !help_overlay_active(Debrief_overlay_id) ) {
		debrief_check_buttons();
		debrief_do_keys(new_k);	
	}

	// blit help overlay if active
	help_overlay_maybe_blit(Debrief_overlay_id, gr_screen.res);

	gr_flip();

	// maybe show skip mission popup
	if ( Must_replay_mission && (!Debrief_skip_popup_already_shown) && (Player->show_skip_popup) && (Game_mode & GM_NORMAL) && (Game_mode & GM_CAMPAIGN_MODE) && (Player->failures_this_session >= PLAYER_MISSION_FAILURE_LIMIT) && !(Game_mode & GM_MULTIPLAYER)) {
		int popup_choice = popup(0, 3, XSTR("Do Not Skip This Mission", 1473),
												 XSTR("Advance To The Next Mission", 1474),
												 XSTR("Don't Show Me This Again", 1475),
												 XSTR("You have failed this mission five times.  If you like, you may advance to the next mission.", 1472) );
		switch (popup_choice) {
		case 0:
			// stay on this mission, so proceed to normal debrief
			// in other words, do nothing.
			break;
		case 1:
			// skip this mission
			mission_campaign_skip_to_next();
			gameseq_post_event(GS_EVENT_START_GAME);
			break;
		case 2:
			// don't show this again
			Player->show_skip_popup = 0;
			break;
		}

		Debrief_skip_popup_already_shown = 1;
	}

	// check to see if we should be showing a pilot info popup in multiplayer (if a guy was double clicked)
	if ((Game_mode & GM_MULTIPLAYER) && Debrief_should_show_popup) {
		Assert((Multi_list_select >= 0) && (Multi_list_select < Multi_list_size));
		multi_pinfo_popup(&Net_players[Multi_list[Multi_list_select].net_player_index]);

		Debrief_should_show_popup = 0;
	}
}

void debrief_rebuild_player_list()
{
	int i;
	net_player *np;
	debrief_multi_list_info *list;

	Multi_list_size = 0;  // number of net players to choose from

	for ( i=0; i<MAX_PLAYERS; i++ ) {
		np = &Net_players[i];
		// remember not to include the standalone.
		if ( MULTI_CONNECTED((*np)) && !MULTI_STANDALONE((*np))){
			list = &Multi_list[Multi_list_size++];
			list->net_player_index = i;
			strcpy_s(list->callsign, np->m_player->callsign);
			
			// make sure to leave some room to blit the team indicator
			font::force_fit_string(list->callsign, CALLSIGN_LEN - 1, Debrief_list_coords[gr_screen.res][2] - MULTI_LIST_TEAM_OFFSET);
		}
	} // end for
}

void debrief_handle_player_drop()
{
	debrief_rebuild_player_list();
}

void debrief_maybe_auto_accept()
{
	if (debrief_can_accept()) {
		debrief_accept(0);
	}
}

void debrief_disable_accept()
{
}

// Goober5000 - replace any variables with their values
// karajorma/jg18 - replace container references as well
// MjnMixael - replace keybinds also
void debrief_replace_stage_text(debrief_stage &stage)
{
	sexp_replace_variable_names_with_values(stage.text);
	sexp_replace_variable_names_with_values(stage.recommendation_text);
	sexp_container_replace_refs_with_values(stage.text);
	sexp_container_replace_refs_with_values(stage.recommendation_text);

	stage.text = message_translate_tokens(stage.text.c_str());
	stage.recommendation_text = message_translate_tokens(stage.recommendation_text.c_str());
}