File: voiceactingmanager.cpp

package info (click to toggle)
freespace2 24.2.0%2Brepack-3
  • links: PTS, VCS
  • area: non-free
  • in suites: forky, sid
  • size: 43,740 kB
  • sloc: cpp: 595,005; ansic: 21,741; python: 1,174; sh: 457; makefile: 243; xml: 181
file content (1242 lines) | stat: -rw-r--r-- 33,290 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
// VoiceActingManager.cpp : implementation file
//

#include "stdafx.h"
#include <string.h>
#include "fred.h"
#include "freddoc.h"
#include "VoiceActingManager.h"
#include "missionui/missioncmdbrief.h"
#include "mission/missionbriefcommon.h"
#include "mission/missionmessage.h"
#include "mission/missiongoals.h"
#include "hud/hudtarget.h"
#include "parse/sexp.h"
#include "iff_defs/iff_defs.h"
#include "mission/missiongoals.h"
#include <math.h>

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#define INVALID_MESSAGE ((MMessage*)SIZE_T_MAX)

// to keep track of data
char Voice_abbrev_briefing[NAME_LENGTH];
char Voice_abbrev_campaign[NAME_LENGTH];
char Voice_abbrev_command_briefing[NAME_LENGTH];
char Voice_abbrev_debriefing[NAME_LENGTH];
char Voice_abbrev_message[NAME_LENGTH];
char Voice_abbrev_mission[NAME_LENGTH];
bool Voice_no_replace_filenames;
char Voice_script_entry_format[NOTES_LENGTH];
int Voice_export_selection;
bool Voice_group_messages;


/////////////////////////////////////////////////////////////////////////////
// VoiceActingManager dialog


VoiceActingManager::VoiceActingManager(CWnd* pParent /*=NULL*/)
	: CDialog(VoiceActingManager::IDD, pParent)
{
	//{{AFX_DATA_INIT(VoiceActingManager)
	m_abbrev_briefing = _T("");
	m_abbrev_campaign = _T("");
	m_abbrev_command_briefing = _T("");
	m_abbrev_debriefing = _T("");
	m_abbrev_message = _T("");
	m_abbrev_mission = _T("");
	m_use_sender_in_filename = FALSE;
	m_example = _T("");
	m_no_replace = FALSE;
	m_script_entry_format = _T("");
	m_export_everything = FALSE;
	m_export_command_briefings = FALSE;
	m_export_briefings = FALSE;
	m_export_debriefings = FALSE;
	m_export_messages = FALSE;
	m_group_messages = FALSE;
	//}}AFX_DATA_INIT
}


void VoiceActingManager::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(VoiceActingManager)
	DDX_Text(pDX, IDC_ABBREV_BRIEFING, m_abbrev_briefing);
	DDX_Text(pDX, IDC_ABBREV_CAMPAIGN, m_abbrev_campaign);
	DDX_Text(pDX, IDC_ABBREV_COMMAND_BRIEFING, m_abbrev_command_briefing);
	DDX_Text(pDX, IDC_ABBREV_DEBRIEFING, m_abbrev_debriefing);
	DDX_Text(pDX, IDC_ABBREV_MESSAGE, m_abbrev_message);
	DDX_Text(pDX, IDC_ABBREV_MISSION, m_abbrev_mission);
	DDX_Text(pDX, IDC_EXAMPLE, m_example);
	DDX_Check(pDX, IDC_NO_REPLACE, m_no_replace);
	DDX_Check(pDX, IDC_INCLUDE_SENDER, m_use_sender_in_filename);
	DDX_Text(pDX, IDC_ENTRY_FORMAT, m_script_entry_format);
	DDX_Check(pDX, IDC_EXPORT_EVERYTHING, m_export_everything);
	DDX_Check(pDX, IDC_EXPORT_COMMAND_BRIEFINGS, m_export_command_briefings);
	DDX_Check(pDX, IDC_EXPORT_BRIEFINGS, m_export_briefings);
	DDX_Check(pDX, IDC_EXPORT_DEBRIEFINGS, m_export_debriefings);
	DDX_Check(pDX, IDC_EXPORT_MESSAGES, m_export_messages);
	DDX_Check(pDX, IDC_GROUP_MESSAGES, m_group_messages);
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(VoiceActingManager, CDialog)
	//{{AFX_MSG_MAP(VoiceActingManager)
	ON_WM_CLOSE()
	ON_EN_SETFOCUS(IDC_ABBREV_BRIEFING, OnSetfocusAbbrevBriefing)
	ON_EN_SETFOCUS(IDC_ABBREV_CAMPAIGN, OnSetfocusAbbrevCampaign)
	ON_EN_SETFOCUS(IDC_ABBREV_COMMAND_BRIEFING, OnSetfocusAbbrevCommandBriefing)
	ON_EN_SETFOCUS(IDC_ABBREV_DEBRIEFING, OnSetfocusAbbrevDebriefing)
	ON_EN_SETFOCUS(IDC_ABBREV_MESSAGE, OnSetfocusAbbrevMessage)
	ON_EN_SETFOCUS(IDC_ABBREV_MISSION, OnSetfocusAbbrevMission)
	ON_CBN_SETFOCUS(IDC_SUFFIX, OnSetfocusSuffix)
	ON_EN_CHANGE(IDC_ABBREV_BRIEFING, OnChangeAbbrevBriefing)
	ON_EN_CHANGE(IDC_ABBREV_CAMPAIGN, OnChangeAbbrevCampaign)
	ON_EN_CHANGE(IDC_ABBREV_COMMAND_BRIEFING, OnChangeAbbrevCommandBriefing)
	ON_EN_CHANGE(IDC_ABBREV_DEBRIEFING, OnChangeAbbrevDebriefing)
	ON_EN_CHANGE(IDC_ABBREV_MESSAGE, OnChangeAbbrevMessage)
	ON_EN_CHANGE(IDC_ABBREV_MISSION, OnChangeAbbrevMission)
	ON_CBN_SELCHANGE(IDC_SUFFIX, OnChangeOtherSuffix)
	ON_BN_CLICKED(IDC_NO_REPLACE, OnChangeNoReplace)
	ON_BN_CLICKED(IDC_GENERATE_FILE_NAMES, OnGenerateFileNames)
	ON_BN_CLICKED(IDC_GENERATE_SCRIPT, OnGenerateScript)
	ON_BN_CLICKED(IDC_EXPORT_EVERYTHING, OnExportEverything)
	ON_BN_CLICKED(IDC_EXPORT_COMMAND_BRIEFINGS, OnExportCommandBriefings)
	ON_BN_CLICKED(IDC_EXPORT_BRIEFINGS, OnExportBriefings)
	ON_BN_CLICKED(IDC_EXPORT_DEBRIEFINGS, OnExportDebriefings)
	ON_BN_CLICKED(IDC_EXPORT_MESSAGES, OnExportMessages)
	ON_BN_CLICKED(IDC_INCLUDE_SENDER, OnBnClickedIncludeSender)
	ON_BN_CLICKED(IDC_MESSAGE_PERSONAS_TO_SHIPS, OnCopyMessagePersonasToShips)
	ON_BN_CLICKED(IDC_SHIP_PERSONAS_TO_MESSAGES, OnCopyShipPersonasToMessages)
	ON_BN_CLICKED(IDC_SET_HEAD_ANIS_USING_MESSAGES_TBL, OnSetHeadANIsUsingMessagesTbl)
	ON_BN_CLICKED(IDC_CLEAR_PERSONAS_FROM_NON_SENDERS, OnClearPersonasFromNonSenders)
	ON_BN_CLICKED(IDC_CHECK_ANY_WINGMAN_PERSONAS, OnCheckAnyWingmanPersonas)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// VoiceActingManager message handlers

BOOL VoiceActingManager::OnInitDialog()
{
	CComboBox *box = ((CComboBox *) GetDlgItem(IDC_SUFFIX));
	box->AddString(".WAV");
	box->AddString(".OGG");
	box->SetCurSel(0);

	// this text is too long for the .rc file, so set it here
	GetDlgItem(IDC_ENTRY_FORMAT_DESC)->SetWindowText(
		"$name - name of the message\r\n"
		"$filename - name of the message file\r\n"
		"$message - text of the message\r\n"
		"$persona - persona of the sender\r\n"
		"$sender - name of the sender\r\n"
		"$note - message notes\r\n\r\n"
		"Note that $persona and $sender will only appear for the Message section."
	);

	// load saved data for file names
	m_abbrev_briefing = _T(Voice_abbrev_briefing);
	m_abbrev_campaign = _T(Voice_abbrev_campaign);
	m_abbrev_command_briefing = _T(Voice_abbrev_command_briefing);
	m_abbrev_debriefing = _T(Voice_abbrev_debriefing);
	m_abbrev_message = _T(Voice_abbrev_message);
	m_abbrev_mission = _T(Voice_abbrev_mission);
	m_no_replace = Voice_no_replace_filenames;

	// load saved data for script
	m_script_entry_format = _T(Voice_script_entry_format);
	m_export_everything = m_export_command_briefings = m_export_briefings = m_export_debriefings = m_export_messages = FALSE;
	if (Voice_export_selection == 1)
		m_export_command_briefings = TRUE;
	else if (Voice_export_selection == 2)
		m_export_briefings = TRUE;
	else if (Voice_export_selection == 3)
		m_export_debriefings = TRUE;
	else if (Voice_export_selection == 4)
		m_export_messages = TRUE;
	else
		m_export_everything = TRUE;
	m_group_messages = Voice_group_messages;
	
	CButton *button = ((CButton *) GetDlgItem(IDC_GROUP_MESSAGES));
	button->EnableWindow(m_export_everything || m_export_messages);

	UpdateData(FALSE);

	return TRUE;
}

void VoiceActingManager::OnClose()
{
	UpdateData(TRUE);

	// save data for file names
	strcpy_s(Voice_abbrev_briefing, m_abbrev_briefing);
	strcpy_s(Voice_abbrev_campaign, m_abbrev_campaign);
	strcpy_s(Voice_abbrev_command_briefing, m_abbrev_command_briefing);
	strcpy_s(Voice_abbrev_debriefing, m_abbrev_debriefing);
	strcpy_s(Voice_abbrev_message, m_abbrev_message);
	strcpy_s(Voice_abbrev_mission, m_abbrev_mission);
	Voice_no_replace_filenames = (m_no_replace == TRUE) ? true : false;

	// save data for script
	strcpy_s(Voice_script_entry_format, m_script_entry_format);
	if (m_export_command_briefings)
		Voice_export_selection = 1;
	else if (m_export_briefings)
		Voice_export_selection = 2;
	else if (m_export_debriefings)
		Voice_export_selection = 3;
	else if (m_export_messages)
		Voice_export_selection = 4;
	else
		Voice_export_selection = 0;
	Voice_group_messages = (m_group_messages == TRUE) ? true : false;

	CDialog::OnClose();
}

CString VoiceActingManager::get_suffix()
{
	// assign suffix
	if (((CComboBox *) GetDlgItem(IDC_SUFFIX))->GetCurSel() == 1)
		return ".ogg";
	else
		return ".wav";
}

int VoiceActingManager::calc_digits(int size)
{
	if (size >= 10000)
		return 5;
	else if (size >= 1000)	// I hope we never hit this!
		return 4;
	else if (size >= 100)
		return 3;
	else
		return 2;
}

void VoiceActingManager::build_example()
{
	// pick a default

	if (m_abbrev_command_briefing != "")
		build_example(m_abbrev_command_briefing);
	else if (m_abbrev_briefing != "")
		build_example(m_abbrev_briefing);
	else if (m_abbrev_debriefing != "")
		build_example(m_abbrev_debriefing);
	else if (m_abbrev_message != "")
		build_example(m_abbrev_message);
	else
		build_example("");
}

void VoiceActingManager::build_example(CString section)
{
	if (section == "")
	{
		m_example = "";
		return;
	}

	m_example = generate_filename(section, 1, 2, INVALID_MESSAGE);
}

CString VoiceActingManager::generate_filename(CString section, int number, int digits, const MMessage *message)
{
	if (section == "")
		return "none.wav";

	int i;
	CString str = "";
	CString num;

	// build prefix
	if (m_abbrev_campaign != "")
		str = str + m_abbrev_campaign;
	if (m_abbrev_mission != "")
		str = str + m_abbrev_mission;
	str = str + section;
	
	// build number
	num.Format("%d", number);;
	digits -= num.GetLength();
	for (i = 0; i < digits; i++)
	{
		num = "0" + num;
	}
	str = str + num;


	const CString suffix = get_suffix();
	// append sender name if supposed to and I have been passed a message
	// to get the sender from
	if ( message != NULL && m_use_sender_in_filename ) {
		size_t allow_to_copy = NAME_LENGTH - suffix.GetLength() - str.GetLength();
		char sender[NAME_LENGTH];
		if ( message == INVALID_MESSAGE ) {
			strcpy_s(sender, "Alpha 1");
		} else {
			get_valid_sender(sender, sizeof(sender), message);
		}

		// truncate sender to that we don't overflow filename
		sender[allow_to_copy] = '\0';
		size_t j;
		for( j = 0; sender[j] != '\0'; j++ ) {
			// lower case letter
			sender[j] = SCP_tolower(sender[j]);

			// replace any non alpha numeric with a underscore
			if ( !isalnum( sender[j] ) )
				sender[j] = '_';
		}

		// flatten multiple underscores
		j = 1;
		while( sender[j] != '\0' ) {
			if ( sender[j-1] == '_' && sender[j] == '_' ) {
				size_t k;
				for (k = j + 1; sender[k] != '\0'; k++ )
					sender[k - 1] = sender[k];
				sender[k - 1] = '\0';
			} else {
				// only increment on rounds when I am not moving the string down
				j++;
			}
		}
		str = str + sender;
	}

	// suffix
	str = str + get_suffix();

	Assert( str.GetLength() < NAME_LENGTH );

	return str;
}

void VoiceActingManager::OnGenerateFileNames() 
{
	int i;
	int digits;
	size_t modified_filenames = 0;

	// stuff data to variables
	UpdateData(TRUE);

	// command briefings
	digits = calc_digits(Cmd_briefs[0].num_stages);
	for (i = 0; i < Cmd_briefs[0].num_stages; i++)
	{
		char *filename = Cmd_briefs[0].stage[i].wave_filename;

		// generate only if we're replacing or if it has a replaceable name
		if (!m_no_replace || !strlen(filename) || message_filename_is_generic(filename))
		{
			strcpy(filename, LPCTSTR(generate_filename(m_abbrev_command_briefing, i + 1, digits)));
			modified_filenames++;
		}
	}

	// briefings
	digits = calc_digits(Briefings[0].num_stages);
	for (i = 0; i < Briefings[0].num_stages; i++)
	{
		char *filename = Briefings[0].stages[i].voice;

		// generate only if we're replacing or if it has a replaceable name
		if (!m_no_replace || !strlen(filename) || message_filename_is_generic(filename))
		{
			strcpy(filename, LPCTSTR(generate_filename(m_abbrev_briefing, i + 1, digits)));
			modified_filenames++;
		}
	}

	// debriefings
	digits = calc_digits(Debriefings[0].num_stages);
	for (i = 0; i < Debriefings[0].num_stages; i++)
	{
		char *filename = Debriefings[0].stages[i].voice;

		// generate only if we're replacing or if it has a replaceable name
		if (!m_no_replace || !strlen(filename) || message_filename_is_generic(filename))
		{
			strcpy(filename, LPCTSTR(generate_filename(m_abbrev_debriefing, i + 1, digits)));
			modified_filenames++;
		}
	}

	// messages
	digits = calc_digits(Num_messages - Num_builtin_messages);
	for (i = 0; i < Num_messages - Num_builtin_messages; i++)
	{
		char *filename = Messages[i + Num_builtin_messages].wave_info.name;
		MMessage *message = &Messages[i + Num_builtin_messages];

		// generate only if we're replacing or if it has a replaceable name
		if (!m_no_replace || !strlen(filename) || message_filename_is_generic(filename))
		{
			// free existing filename
			if (filename != NULL)
				free(filename);

			// allocate new filename
			Messages[i + Num_builtin_messages].wave_info.name = strdup(LPCTSTR(generate_filename(m_abbrev_message, i + 1, digits, message)));
			modified_filenames++;
		}
	}

	if ( modified_filenames > 0 ) {
		// Tell FRED that we actually modified something
		set_modified(TRUE);
	}

	// notify user that we are done and how many filenames were changed
	SCP_string message;
	sprintf(message, "File name generation complete.  " SIZE_T_ARG " file %s modified.", modified_filenames, (modified_filenames == 1) ? "name was" : "names were");
	MessageBox(message.c_str(), "Voice Acting Manager");
}

void VoiceActingManager::OnGenerateScript()
{
	char pathname[256];

	// stuff data to variables
	UpdateData(TRUE);

	// prompt to save script
	CFileDialog dlg(FALSE, "txt", NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "Text files (*.txt)|*.txt||");
	if (dlg.DoModal() != IDOK)
		return;

	CString dlgPathName = dlg.GetPathName( );
	string_copy(pathname, dlgPathName, 256 - 1);
	fp = cfopen(pathname, "wt", CFILE_NORMAL);
	if (!fp)
	{
		MessageBox("Can't open file to save.", "Error!");
		return;
	}

	fout("%s\n", Mission_filename);
	fout("%s\n\n", The_mission.name);

	if (m_export_everything || m_export_command_briefings)
	{
		fout("\n\nCommand Briefings\n-----------------\n\n");

		for (int i = 0; i < Cmd_briefs[0].num_stages; i++)
		{
			CString entry = m_script_entry_format;
			entry.Replace("\r\n", "\n");

			cmd_brief_stage *stage = &Cmd_briefs[0].stage[i];
			entry.Replace("$filename", stage->wave_filename);
			entry.Replace("$message", stage->text.c_str());
			entry.Replace("$persona", "<no persona specified>");
			entry.Replace("$sender", "<no sender specified>");
			entry.Replace("$name", "<no name specified>");
			entry.Replace("$note", "<no note specified>");

			fout("%s\n\n\n", (char *) (LPCTSTR) entry);
		}
	}

	if (m_export_everything || m_export_briefings)
	{
		fout("\n\nBriefings\n---------\n\n");

		for (int i = 0; i < Briefings[0].num_stages; i++)
		{
			CString entry = m_script_entry_format;
			entry.Replace("\r\n", "\n");

			brief_stage *stage = &Briefings[0].stages[i];
			entry.Replace("$filename", stage->voice);
			entry.Replace("$message", stage->text.c_str());
			entry.Replace("$persona", "<no persona specified>");
			entry.Replace("$sender", "<no sender specified>");
			entry.Replace("$name", "<no name specified>");
			entry.Replace("$note", "<no note specified>");

			fout("%s\n\n\n", (char *) (LPCTSTR) entry);
		}
	}

	if (m_export_everything || m_export_debriefings)
	{
		fout("\n\nDebriefings\n-----------\n\n");

		for (int i = 0; i < Debriefings[0].num_stages; i++)
		{
			CString entry = m_script_entry_format;
			entry.Replace("\r\n", "\n");

			debrief_stage *stage = &Debriefings[0].stages[i];
			entry.Replace("$filename", stage->voice);
			entry.Replace("$message", stage->text.c_str());
			entry.Replace("$persona", "<no persona specified>");
			entry.Replace("$sender", "<no sender specified>");
			entry.Replace("$name", "<no name specified>");
			entry.Replace("$note", "<no note specified>");
	
			fout("%s\n\n\n", (char *) (LPCTSTR) entry);
		}
	}

	if (m_export_everything || m_export_messages)
	{
		fout("\n\nMessages\n--------\n\n");

		if (m_group_messages)
		{
			SCP_vector<int> message_indexes;
			for (int i = 0; i < Num_messages - Num_builtin_messages; i++)
				message_indexes.push_back(i + Num_builtin_messages);

			group_message_indexes(message_indexes);

			for (size_t index = 0; index < message_indexes.size(); index++)
			{
				MMessage *message = &Messages[message_indexes[index]];
				export_one_message(message);
			}
		}
		else
		{
			for (int i = 0; i < Num_messages - Num_builtin_messages; i++)
			{
				MMessage *message = &Messages[i + Num_builtin_messages];
				export_one_message(message);
			}
		}
	}

	cfclose(fp);

	// notify
	MessageBox("Script generation complete.", "Woohoo!");
}

void VoiceActingManager::export_one_message(const MMessage *message)
{
	CString entry = m_script_entry_format;
	entry.Replace("\r\n", "\n");

	entry.Replace("$name", message->name);

	// replace file name
	entry.Replace("$filename", message->wave_info.name);

	// replace message
	entry.Replace("$message", message->message);

	entry.Replace("$note", message->note.c_str());

	// determine and replace persona
	if (message->persona_index >= 0)
		entry.Replace("$persona", Personas[message->persona_index].name);
	else
		entry.Replace("$persona", "<none>");

	// determine sender
	char sender[NAME_LENGTH+1];
	get_valid_sender(sender, sizeof(sender), message);

	// replace sender (but print #Command as Command)
	if (*sender == '#')
		entry.Replace("$sender", &sender[1]);
	else
		entry.Replace("$sender", sender);

	fout("%s\n\n\n", (char *) (LPCTSTR) entry);
}

/** Passed sender string will have either have the senders name
or '\<none\>'*/
void VoiceActingManager::get_valid_sender(char *sender, size_t sender_size, const MMessage *message, int *sender_shipnum)
{
	Assert( sender != NULL );
	Assert( message != NULL );

	memset(sender, 0, sender_size);
	strncpy(sender, get_message_sender(message), sender_size - 1);

	// check if we're overriding #Command
	if (The_mission.flags[Mission::Mission_Flags::Override_hashcommand] && !strcmp("#Command", sender))
	{
		memset(sender, 0, sender_size);
		strncpy(sender, The_mission.command_sender, sender_size - 1);
	}

	// strip hash if present
	if ( sender[0] == '#' )
	{
		size_t i = 1;
		for(; sender[i] != '\0'; i++ ) {
			sender[i-1] = sender[i];
		}
		sender[i-1] = '\0';
	}

	int shipnum = ship_name_lookup(sender, 1); // The player's ship is valid for this search.

	if (sender_shipnum != nullptr)
		*sender_shipnum = shipnum;

	if (shipnum >= 0)
	{
		ship *shipp = &Ships[shipnum];

		// we may have to use the callsign
		if (*Fred_callsigns[shipnum])
		{
			hud_stuff_ship_callsign(sender, shipp);
		}
		// account for hidden ship names
		else if ( ((Iff_info[shipp->team].flags & IFFF_WING_NAME_HIDDEN) && (shipp->wingnum != -1)) || (shipp->flags[Ship::Ship_Flags::Hide_ship_name]) )
		{
			hud_stuff_ship_class(sender, shipp);
		}
		// use the regular sender display name
		else
		{
			memset(sender, 0, sender_size);
			strncpy(sender, shipp->get_display_name(), sender_size - 1);
		}
	}
}

void VoiceActingManager::OnSetfocusAbbrevBriefing() 
{
	UpdateData(TRUE);

	build_example(m_abbrev_briefing);

	UpdateData(FALSE);
}

void VoiceActingManager::OnSetfocusAbbrevCampaign() 
{
	UpdateData(TRUE);

	build_example();

	UpdateData(FALSE);
}

void VoiceActingManager::OnSetfocusAbbrevCommandBriefing() 
{
	UpdateData(TRUE);

	build_example(m_abbrev_command_briefing);

	UpdateData(FALSE);
}

void VoiceActingManager::OnSetfocusAbbrevDebriefing() 
{
	UpdateData(TRUE);

	build_example(m_abbrev_debriefing);

	UpdateData(FALSE);
}

void VoiceActingManager::OnSetfocusAbbrevMessage() 
{
	UpdateData(TRUE);

	build_example(m_abbrev_message);

	UpdateData(FALSE);
}

void VoiceActingManager::OnSetfocusAbbrevMission() 
{
	UpdateData(TRUE);

	build_example();

	UpdateData(FALSE);
}

void VoiceActingManager::OnSetfocusSuffix()
{
	UpdateData(TRUE);

	build_example();

	UpdateData(FALSE);
}

void VoiceActingManager::OnChangeAbbrevBriefing() 
{
	UpdateData(TRUE);

	build_example(m_abbrev_briefing);

	UpdateData(FALSE);
}

void VoiceActingManager::OnChangeAbbrevCampaign() 
{
	UpdateData(TRUE);

	build_example();

	UpdateData(FALSE);
}

void VoiceActingManager::OnChangeAbbrevCommandBriefing() 
{
	UpdateData(TRUE);

	build_example(m_abbrev_command_briefing);

	UpdateData(FALSE);
}

void VoiceActingManager::OnChangeAbbrevDebriefing() 
{
	UpdateData(TRUE);

	build_example(m_abbrev_debriefing);

	UpdateData(FALSE);
}

void VoiceActingManager::OnChangeAbbrevMessage() 
{
	UpdateData(TRUE);

	build_example(m_abbrev_message);

	UpdateData(FALSE);
}

void VoiceActingManager::OnChangeAbbrevMission() 
{
	UpdateData(TRUE);

	build_example();

	UpdateData(FALSE);
}

void VoiceActingManager::OnChangeOtherSuffix() 
{
	UpdateData(TRUE);

	build_example();

	UpdateData(FALSE);
}

void VoiceActingManager::OnChangeNoReplace()
{
	UpdateData(TRUE);
}

int VoiceActingManager::fout(const char *format, ...)
{
	SCP_string str;
	va_list args;
	
	va_start(args, format);
	vsprintf(str, format, args);
	va_end(args);

	cfputs(str.c_str(), fp);
	return 0;
}

// Loops through all the sexps and finds the sender of the specified message.  This assumes there is only one possible
// sender of the message, which is probably nearly always true (especially for voice-acted missions).
const char *VoiceActingManager::get_message_sender(const MMessage *message)
{
	int i;

	for (i = 0; i < Num_sexp_nodes; i++)
	{
		if (Sexp_nodes[i].type == SEXP_NOT_USED)
			continue;

		// stuff
		int op = get_operator_const(i);
		int n = CDR(i);

		// find the message sexps
		if (op == OP_SEND_MESSAGE)
		{
			// the first argument is the sender; the third is the message
			if (!strcmp(message->name, Sexp_nodes[CDDR(n)].text))
				return Sexp_nodes[n].text;
		}
		else if (op == OP_SEND_MESSAGE_LIST || op == OP_SEND_MESSAGE_CHAIN)
		{
			// skip the event argument
			if (op == OP_SEND_MESSAGE_CHAIN)
				n = CDR(n);

			// check the argument list
			while (n != -1)
			{
				// as before
				if (!strcmp(message->name, Sexp_nodes[CDDR(n)].text))
					return Sexp_nodes[n].text;

				// iterate along the list
				n = CDDDDR(n);
			}
		}
		else if (op == OP_SEND_RANDOM_MESSAGE)
		{
			// as before, sort of
			char *sender = Sexp_nodes[n].text;

			// check the argument list
			n = CDDR(n);
			while (n != -1)
			{
				if (!strcmp(message->name, Sexp_nodes[n].text))
					return sender;

				// iterate along the list
				n = CDR(n);
			}
		}
		else if (op == OP_TRAINING_MSG)
		{
			// just check the message
			if (!strcmp(message->name, Sexp_nodes[n].text))
				return "Training Message";
		}
	}

	return "<none>";
}

void VoiceActingManager::group_message_indexes(SCP_vector<int> &message_indexes)
{
#ifndef NDEBUG
	size_t initial_size = message_indexes.size();
#endif

	SCP_vector<int> temp_message_indexes = message_indexes;
	message_indexes.clear();

	// add all messages found in send-message-list or send-random-message node trees
	for (const auto &event: Mission_events)
		group_message_indexes_in_tree(event.formula, temp_message_indexes, message_indexes);

	// add remaining messages
	for (size_t index = 0; index < temp_message_indexes.size(); index++)
		message_indexes.push_back(temp_message_indexes[index]);

#ifndef NDEBUG
	if (initial_size > message_indexes.size())
	{
		Warning(LOCATION, "Initial size is greater than size after sorting!");
	}
	else if (initial_size < message_indexes.size())
	{
		Warning(LOCATION, "Initial size is less than size after sorting!");
	}
#endif
}

void VoiceActingManager::group_message_indexes_in_tree(int node, SCP_vector<int> &source_list, SCP_vector<int> &destination_list)
{
	int op, n;

	if (node < 0)
		return;
	if (Sexp_nodes[node].type == SEXP_NOT_USED)
		return;

	// stuff
	op = get_operator_const(node);
	n = CDR(node);

	if (op == OP_SEND_MESSAGE_LIST || op == OP_SEND_MESSAGE_CHAIN)
	{
		// skip the event argument
		if (op == OP_SEND_MESSAGE_CHAIN)
			n = CDR(n);

		// check the argument list
		while (n != -1)
		{
			// the third argument is a message
			char *message_name = Sexp_nodes[CDDR(n)].text;

			// check source messages
			for (size_t i = 0; i < source_list.size(); i++)
			{
				if (!strcmp(message_name, Messages[source_list[i]].name))
				{
					// move it from source to destination
					destination_list.push_back(source_list[i]);
					source_list.erase(source_list.begin() + i);
					break;
				}
			}

			// iterate along the list
			n = CDDDDR(n);
		}
	}
	else if (op == OP_SEND_RANDOM_MESSAGE)
	{
		// check the argument list
		n = CDDR(n);
		while (n != -1)
		{
			// each argument from this point on is a message
			char *message_name = Sexp_nodes[n].text;

			// check source messages
			for (size_t i = 0; i < source_list.size(); i++)
			{
				if (!strcmp(message_name, Messages[source_list[i]].name))
				{
					// move it from source to destination
					destination_list.push_back(source_list[i]);
					source_list.erase(source_list.begin() + i);
					break;
				}
			}

			// iterate along the list
			n = CDR(n);
		}
	}

	// iterate on first element
	group_message_indexes_in_tree(CAR(node), source_list, destination_list);

	// iterate on rest of elements
	group_message_indexes_in_tree(CDR(node), source_list, destination_list);
}

void VoiceActingManager::OnExportEverything()
{
	CButton *button = ((CButton *) GetDlgItem(IDC_GROUP_MESSAGES));
	button->EnableWindow(TRUE);
}

void VoiceActingManager::OnExportCommandBriefings()
{
	CButton *button = ((CButton *) GetDlgItem(IDC_GROUP_MESSAGES));
	button->EnableWindow(FALSE);
}

void VoiceActingManager::OnExportBriefings()
{
	CButton *button = ((CButton *) GetDlgItem(IDC_GROUP_MESSAGES));
	button->EnableWindow(FALSE);
}

void VoiceActingManager::OnExportDebriefings()
{
	CButton *button = ((CButton *) GetDlgItem(IDC_GROUP_MESSAGES));
	button->EnableWindow(FALSE);
}

void VoiceActingManager::OnExportMessages()
{
	CButton *button = ((CButton *) GetDlgItem(IDC_GROUP_MESSAGES));
	button->EnableWindow(TRUE);
}

void VoiceActingManager::OnBnClickedIncludeSender()
{
	UpdateData(TRUE);

	build_example();

	UpdateData(FALSE);
}

void VoiceActingManager::OnCopyPersonas(bool messages_to_ships)
{
	char sender_buf[NAME_LENGTH];
	int sender_shipnum;
	size_t num_modified = 0;

	SCP_unordered_set<int> already_assigned;
	SCP_string inconsistent_copy_msg;

	// go through all messages in the mission
	for (int i = 0; i < Num_messages - Num_builtin_messages; i++)
	{
		auto message = &Messages[i + Num_builtin_messages];

		// find whoever sent this message
		get_valid_sender(sender_buf, NAME_LENGTH, message, &sender_shipnum);

		// if it's a ship, copy the persona
		if (sender_shipnum >= 0)
		{
			auto sender_shipp = &Ships[sender_shipnum];
			auto persona_to_copy = (messages_to_ships) ? message->persona_index : sender_shipp->persona_index;

			// don't copy None, and only copy wingman personas
			if (persona_to_copy >= 0 && (Personas[persona_to_copy].flags & PERSONA_FLAG_WINGMAN))
			{
				if (messages_to_ships)
				{
					if (already_assigned.count(sender_shipnum) > 0 && sender_shipp->persona_index != persona_to_copy)
					{
						inconsistent_copy_msg += "\n\u2022 ";
						inconsistent_copy_msg += sender_shipp->ship_name;
					}

					sender_shipp->persona_index = persona_to_copy;
					already_assigned.insert(sender_shipnum);
					num_modified++;
				}
				else
				{
					if (already_assigned.count(i) > 0 && message->persona_index != persona_to_copy)
					{
						inconsistent_copy_msg += "\n\u2022 ";
						inconsistent_copy_msg += message->name;
					}

					message->persona_index = persona_to_copy;
					already_assigned.insert(i);
					num_modified++;
				}
			}
		}
	}

	if (num_modified > 0)
		set_modified(TRUE);

	SCP_string message;
	if (messages_to_ships)
		sprintf(message, "Personas have been copied from messages to ships.  " SIZE_T_ARG " %s modified.", num_modified, (num_modified == 1) ? "ship was" : "ships were");
	else
		sprintf(message, "Personas have been copied from ships to messages.  " SIZE_T_ARG " %s modified.", num_modified, (num_modified == 1) ? "message was" : "messages were");

	if (!inconsistent_copy_msg.empty())
	{
		if (messages_to_ships)
			message += "\n\nThe following ships send messages with inconsistent personas.  You may want to review them.\n";
		else
			message += "\n\nThe following messages are sent by ships with inconsistent personas.  You may want to review them.\n";
		message += inconsistent_copy_msg;
	}

	MessageBox(message.c_str(), "Voice Acting Manager");
}

void VoiceActingManager::OnClearPersonasFromNonSenders()
{
	SCP_unordered_set<int> all_senders;

	char sender_buf[NAME_LENGTH];
	int sender_shipnum;
	size_t num_modified = 0;

	// go through all messages in the mission
	for (int i = 0; i < Num_messages - Num_builtin_messages; i++)
	{
		auto message = &Messages[i + Num_builtin_messages];

		// find whoever sent this message
		get_valid_sender(sender_buf, NAME_LENGTH, message, &sender_shipnum);

		// if it's a ship, save the shipnum
		if (sender_shipnum >= 0)
			all_senders.insert(sender_shipnum);
	}

	// go through all ships in the mission
	for (auto objp : list_range(&obj_used_list))
	{
		if ((objp->type == OBJ_START) || (objp->type == OBJ_SHIP))
		{
			// for ships that aren't message senders
			if (all_senders.count(objp->instance) == 0)
			{
				// only clear wingman personas
				if ((Ships[objp->instance].persona_index >= 0) && (Personas[Ships[objp->instance].persona_index].flags & PERSONA_FLAG_WINGMAN))
				{
					// clear the persona
					Ships[objp->instance].persona_index = -1;
					num_modified++;
				}
			}
		}
	}

	if (num_modified > 0)
		set_modified(TRUE);

	SCP_string message;
	sprintf(message, "Personas have been cleared from all ships that do not send messages.  " SIZE_T_ARG " %s modified.", num_modified, (num_modified == 1) ? "ship was" : "ships were");
	MessageBox(message.c_str(), "Voice Acting Manager");
}

void VoiceActingManager::OnCopyMessagePersonasToShips()
{
	OnCopyPersonas(true);
}

void VoiceActingManager::OnCopyShipPersonasToMessages()
{
	OnCopyPersonas(false);
}

void VoiceActingManager::OnSetHeadANIsUsingMessagesTbl()
{
	size_t num_modified = 0;

	// go through all messages in the mission
	for (int i = 0; i < Num_messages - Num_builtin_messages; i++)
	{
		auto message = &Messages[i + Num_builtin_messages];

		// only messages with personas
		if (message->persona_index < 0)
			continue;

		// only wingman personas
		if (!(Personas[message->persona_index].flags & PERSONA_FLAG_WINGMAN))
			continue;

		// find the corresponding head for this persona
		bool found = false;
		for (int j = 0; j < Num_builtin_messages; j++)
		{
			auto builtin_message = &Messages[j];

			if (message->persona_index == builtin_message->persona_index)
			{
				// either assign the correct head from scratch, or change the head to the correct one
				if (message->avi_info.name == nullptr)
				{
					message->avi_info.name = strdup(builtin_message->avi_info.name);
					num_modified++;
				}
				else if (stricmp(message->avi_info.name, builtin_message->avi_info.name) != 0)
				{
					free(message->avi_info.name);
					message->avi_info.name = strdup(builtin_message->avi_info.name);
					num_modified++;
				}

				// done searching
				found = true;
				break;
			}
		}

		if (!found)
		{
			Warning(LOCATION, "Persona index %d was not found in list of messages.tbl personas!", message->persona_index);
		}
	}

	if (num_modified > 0)
		set_modified(TRUE);

	SCP_string message;
	sprintf(message, "Message head ANIs have been assigned from builtin messages.  " SIZE_T_ARG " %s modified.", num_modified, (num_modified == 1) ? "message was" : "messages were");
	MessageBox(message.c_str(), "Voice Acting Manager");
}

void VoiceActingManager::OnCheckAnyWingmanPersonas()
{
	char sender_buf[NAME_LENGTH];
	SCP_string output_msg;
	bool any_any_wingman = false;
	int issue_count = 0;

	// go through all messages in the mission
	for (int i = 0; i < Num_messages - Num_builtin_messages; i++)
	{
		auto message = &Messages[i + Num_builtin_messages];

		// find whoever sent this message
		get_valid_sender(sender_buf, NAME_LENGTH, message);

		// only check <any wingman>
		if (stricmp(sender_buf, "<any wingman>") != 0)
			continue;
		any_any_wingman = true;

		// check the message itself
		if (message->persona_index < 0)
		{
			issue_count++;
			output_msg += "\n\"";
			output_msg += message->name;
			output_msg += "\" - does not have a persona";
			continue;
		}
		if (!(Personas[message->persona_index].flags & PERSONA_FLAG_WINGMAN))
		{
			issue_count++;
			output_msg += "\n\"";
			output_msg += message->name;
			output_msg += "\" - does not have a wingman persona";
			continue;
		}

		bool found_potential_sender = false;

		// go through all ships in the mission
		for (auto objp : list_range(&obj_used_list))
		{
			if ((objp->type == OBJ_START) || (objp->type == OBJ_SHIP))
			{
				if (Ships[objp->instance].persona_index == message->persona_index)
				{
					found_potential_sender = true;
					break;
				}
			}
		}

		if (!found_potential_sender)
		{
			issue_count++;
			output_msg += "\n\"";
			output_msg += message->name;
			output_msg += "\" - no ship with persona \"";
			output_msg += Personas[message->persona_index].name;
			output_msg += "\" was found";
		}
	}

	if (!output_msg.empty())
	{
		if (issue_count == 1)
			output_msg = "The following issue was found for messages sent by <any wingman>:\n" + output_msg;
		else
			output_msg = "The following issues were found for messages sent by <any wingman>:\n" + output_msg;

		MessageBox(output_msg.c_str(), "Voice Acting Manager");
	}
	else if (!any_any_wingman)
		MessageBox("All messages have been checked.  There are no messages sent by <any wingman>.", "Voice Acting Manager");
	else
		MessageBox("All messages have been checked.  All messages sent by <any wingman> have at least one candidate sender.", "Voice Acting Manager");
}