aboutsummaryrefslogtreecommitdiff
path: root/base/commandLine.cpp
blob: e1576a0fad0eda7f22b9007ad67144eb6a8fad84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

// FIXME: Avoid using printf
#define FORBIDDEN_SYMBOL_EXCEPTION_printf

#define FORBIDDEN_SYMBOL_EXCEPTION_exit

#include <limits.h>

#include "engines/metaengine.h"
#include "base/commandLine.h"
#include "base/plugins.h"
#include "base/version.h"

#include "common/config-manager.h"
#include "common/fs.h"
#include "common/rendermode.h"
#include "common/stack.h"
#include "common/system.h"
#include "common/textconsole.h"

#include "gui/ThemeEngine.h"

#include "audio/musicplugin.h"

#define DETECTOR_TESTING_HACK
#define UPGRADE_ALL_TARGETS_HACK

namespace Base {

#ifndef DISABLE_COMMAND_LINE

static const char USAGE_STRING[] =
	"%s: %s\n"
	"Usage: %s [OPTIONS]... [GAME]\n"
	"\n"
	"Try '%s --help' for more options.\n"
;

// DONT FIXME: DO NOT ORDER ALPHABETICALLY, THIS IS ORDERED BY IMPORTANCE/CATEGORY! :)
#if defined(__SYMBIAN32__) || defined(__GP32__) || defined(ANDROID) || defined(__DS__) || defined(__3DS__)
static const char HELP_STRING[] = "NoUsageString"; // save more data segment space
#else
static const char HELP_STRING[] =
	"ScummVM - Graphical Adventure Game Interpreter\n"
	"Usage: %s [OPTIONS]... [GAME]\n"
	"  -v, --version            Display ScummVM version information and exit\n"
	"  -h, --help               Display a brief help text and exit\n"
	"  -z, --list-games         Display list of supported games and exit\n"
	"  -t, --list-targets       Display list of configured targets and exit\n"
	"  --list-saves=TARGET      Display a list of saved games for the game (TARGET) specified\n"
	"  -a, --add                Add all games from current or specified directory.\n"
	"                           If --game=ID is passed only the game with id ID is added. See also --detect\n"
	"                           Use --path=PATH before -a, --add to specify a directory.\n"
	"  --detect                 Display a list of games with their ID from current or\n"
	"                           specified directory without adding it to the config.\n"
	"                           Use --path=PATH before --detect to specify a directory.\n"
	"  --game=ID                In combination with --add or --detect only adds or attempts to\n"
	"                           detect the game with id ID.\n"
	"  --auto-detect            Display a list of games from current or specified directory\n"
	"                           and start the first one. Use --path=PATH before --auto-detect\n"
	"                           to specify a directory.\n"
	"  --recursive              In combination with --add or --detect recurse down all subdirectories\n"
#if defined(WIN32) && !defined(_WIN32_WCE) && !defined(__SYMBIAN32__)
	"  --console                Enable the console window (default:enabled)\n"
#endif
	"\n"
	"  -c, --config=CONFIG      Use alternate configuration file\n"
	"  -p, --path=PATH          Path to where the game is installed\n"
	"  -x, --save-slot[=NUM]    Save game slot to load (default: autosave)\n"
	"  -f, --fullscreen         Force full-screen mode\n"
	"  -F, --no-fullscreen      Force windowed mode\n"
	"  -g, --gfx-mode=MODE      Select graphics scaler (1x,2x,3x,2xsai,super2xsai,\n"
	"                           supereagle,advmame2x,advmame3x,hq2x,hq3x,tv2x,\n"
	"                           dotmatrix)\n"
	"  --filtering              Force filtered graphics mode\n"
	"  --no-filtering           Force unfiltered graphics mode\n"
	"  --gui-theme=THEME        Select GUI theme\n"
	"  --themepath=PATH         Path to where GUI themes are stored\n"
	"  --list-themes            Display list of all usable GUI themes\n"
	"  -e, --music-driver=MODE  Select music driver (see README for details)\n"
	"  --list-audio-devices     List all available audio devices\n"
	"  -q, --language=LANG      Select language (en,de,fr,it,pt,es,jp,zh,kr,se,gb,\n"
	"                           hb,ru,cz)\n"
	"  -m, --music-volume=NUM   Set the music volume, 0-255 (default: 192)\n"
	"  -s, --sfx-volume=NUM     Set the sfx volume, 0-255 (default: 192)\n"
	"  -r, --speech-volume=NUM  Set the speech volume, 0-255 (default: 192)\n"
	"  --midi-gain=NUM          Set the gain for MIDI playback, 0-1000 (default:\n"
	"                           100) (only supported by some MIDI drivers)\n"
	"  -n, --subtitles          Enable subtitles (use with games that have voice)\n"
	"  -b, --boot-param=NUM     Pass number to the boot script (boot param)\n"
	"  -d, --debuglevel=NUM     Set debug verbosity level\n"
	"  --debugflags=FLAGS       Enable engine specific debug flags\n"
	"                           (separated by commas)\n"
	"  --debug-channels-only    Show only the specified debug channels\n"
	"  -u, --dump-scripts       Enable script dumping if a directory called 'dumps'\n"
	"                           exists in the current directory\n"
	"\n"
	"  --cdrom=DRIVE            CD drive to play CD audio from; can either be a\n"
	"                           drive, path, or numeric index (default: 0 = best\n"
	"                           choice drive)\n"
	"  --joystick[=NUM]         Enable joystick input (default: 0 = first joystick)\n"
	"  --platform=WORD          Specify platform of game (allowed values: 2gs, 3do,\n"
	"                           acorn, amiga, atari, c64, fmtowns, nes, mac, pc, pc98,\n"
	"                           pce, segacd, wii, windows)\n"
	"  --savepath=PATH          Path to where saved games are stored\n"
	"  --extrapath=PATH         Extra path to additional game data\n"
	"  --soundfont=FILE         Select the SoundFont for MIDI playback (only\n"
	"                           supported by some MIDI drivers)\n"
	"  --multi-midi             Enable combination AdLib and native MIDI\n"
	"  --native-mt32            True Roland MT-32 (disable GM emulation)\n"
	"  --enable-gs              Enable Roland GS mode for MIDI playback\n"
	"  --output-rate=RATE       Select output sample rate in Hz (e.g. 22050)\n"
	"  --opl-driver=DRIVER      Select AdLib (OPL) emulator (db, mame"
#ifndef DISABLE_NUKED_OPL
                                                                     ", nuked"
#endif
#ifdef ENABLE_OPL2LPT
                                                                     ", opl2lpt"
#endif
                                                                              ")\n"
	"  --aspect-ratio           Enable aspect ratio correction\n"
	"  --render-mode=MODE       Enable additional render modes (hercGreen, hercAmber,\n"
	"                           cga, ega, vga, amiga, fmtowns, pc9821, pc9801, 2gs,\n"
	"                           atari, macintosh)\n"
#ifdef ENABLE_EVENTRECORDER
	"  --record-mode=MODE       Specify record mode for event recorder (record, playback,\n"
	"                           passthrough [default])\n"
	"  --record-file-name=FILE  Specify record file name\n"
	"  --disable-display        Disable any gfx output. Used for headless events\n"
	"                           playback by Event Recorder\n"
#endif
	"\n"
#if defined(ENABLE_SKY) || defined(ENABLE_QUEEN)
	"  --alt-intro              Use alternative intro for CD versions of Beneath a\n"
	"                           Steel Sky and Flight of the Amazon Queen\n"
#endif
	"  --copy-protection        Enable copy protection in games, when\n"
	"                           ScummVM disables it by default.\n"
	"  --talkspeed=NUM          Set talk speed for games (default: 60)\n"
#if defined(ENABLE_SCUMM) || defined(ENABLE_GROOVIE)
	"  --demo-mode              Start demo mode of Maniac Mansion or The 7th Guest\n"
#endif
#if defined(ENABLE_DIRECTOR)
	"  --start-movie=NAME       Start movie for Director\n"
#endif
#ifdef ENABLE_SCUMM
	"  --tempo=NUM              Set music tempo (in percent, 50-200) for SCUMM games\n"
	"                           (default: 100)\n"
#ifdef ENABLE_SCUMM_7_8
	"  --dimuse-tempo=NUM       Set internal Digital iMuse tempo (10 - 100) per second\n"
	"                           (default: 10)\n"
#endif
#endif
	"\n"
	"The meaning of boolean long options can be inverted by prefixing them with\n"
	"\"no-\", e.g. \"--no-aspect-ratio\".\n"
;
#endif

static const char *s_appName = "scummvm";

static void NORETURN_PRE usage(const char *s, ...) GCC_PRINTF(1, 2) NORETURN_POST;

static void usage(const char *s, ...) {
	char buf[STRINGBUFLEN];
	va_list va;

	va_start(va, s);
	vsnprintf(buf, STRINGBUFLEN, s, va);
	va_end(va);

#if !(defined(__GP32__) || defined(__SYMBIAN32__) || defined(__DS__))
	printf(USAGE_STRING, s_appName, buf, s_appName, s_appName);
#endif
	exit(1);
}

#endif // DISABLE_COMMAND_LINE


void registerDefaults() {

	// Graphics
	ConfMan.registerDefault("fullscreen", false);
	ConfMan.registerDefault("filtering", false);
	ConfMan.registerDefault("aspect_ratio", false);
	ConfMan.registerDefault("gfx_mode", "normal");
	ConfMan.registerDefault("render_mode", "default");
	ConfMan.registerDefault("desired_screen_aspect_ratio", "auto");

	// Sound & Music
	ConfMan.registerDefault("music_volume", 192);
	ConfMan.registerDefault("sfx_volume", 192);
	ConfMan.registerDefault("speech_volume", 192);

	ConfMan.registerDefault("music_mute", false);
	ConfMan.registerDefault("sfx_mute", false);
	ConfMan.registerDefault("speech_mute", false);
	ConfMan.registerDefault("mute", false);

	ConfMan.registerDefault("multi_midi", false);
	ConfMan.registerDefault("native_mt32", false);
	ConfMan.registerDefault("enable_gs", false);
	ConfMan.registerDefault("midi_gain", 100);

	ConfMan.registerDefault("music_driver", "auto");
	ConfMan.registerDefault("mt32_device", "null");
	ConfMan.registerDefault("gm_device", "null");
	ConfMan.registerDefault("opl2lpt_parport", "null");

	ConfMan.registerDefault("cdrom", 0);

	ConfMan.registerDefault("enable_unsupported_game_warning", true);

	// Game specific
	ConfMan.registerDefault("path", "");
	ConfMan.registerDefault("platform", Common::kPlatformDOS);
	ConfMan.registerDefault("language", "en");
	ConfMan.registerDefault("subtitles", false);
	ConfMan.registerDefault("boot_param", 0);
	ConfMan.registerDefault("dump_scripts", false);
	ConfMan.registerDefault("save_slot", -1);
	ConfMan.registerDefault("autosave_period", 5 * 60);	// By default, trigger autosave every 5 minutes

#if defined(ENABLE_SCUMM) || defined(ENABLE_SWORD2)
	ConfMan.registerDefault("object_labels", true);
#endif

	ConfMan.registerDefault("copy_protection", false);
	ConfMan.registerDefault("talkspeed", 60);

#if defined(ENABLE_SCUMM) || defined(ENABLE_GROOVIE)
	ConfMan.registerDefault("demo_mode", false);
#endif
#ifdef ENABLE_SCUMM
	ConfMan.registerDefault("tempo", 0);
#ifdef ENABLE_SCUMM_7_8
	ConfMan.registerDefault("dimuse_tempo", 10);
#endif
#endif

#if defined(ENABLE_SKY) || defined(ENABLE_QUEEN)
	ConfMan.registerDefault("alt_intro", false);
#endif

	// Miscellaneous
	ConfMan.registerDefault("joystick_num", -1);
	ConfMan.registerDefault("confirm_exit", false);
	ConfMan.registerDefault("disable_sdl_parachute", false);

	ConfMan.registerDefault("disable_display", false);
	ConfMan.registerDefault("record_mode", "none");
	ConfMan.registerDefault("record_file_name", "record.bin");

	ConfMan.registerDefault("gui_saveload_chooser", "grid");
	ConfMan.registerDefault("gui_saveload_last_pos", "0");

	ConfMan.registerDefault("gui_browser_show_hidden", false);
	ConfMan.registerDefault("game", "");

#ifdef USE_FLUIDSYNTH
	// The settings are deliberately stored the same way as in Qsynth. The
	// FluidSynth music driver is responsible for transforming them into
	// their appropriate values.
	ConfMan.registerDefault("fluidsynth_chorus_activate", true);
	ConfMan.registerDefault("fluidsynth_chorus_nr", 3);
	ConfMan.registerDefault("fluidsynth_chorus_level", 100);
	ConfMan.registerDefault("fluidsynth_chorus_speed", 30);
	ConfMan.registerDefault("fluidsynth_chorus_depth", 80);
	ConfMan.registerDefault("fluidsynth_chorus_waveform", "sine");

	ConfMan.registerDefault("fluidsynth_reverb_activate", true);
	ConfMan.registerDefault("fluidsynth_reverb_roomsize", 20);
	ConfMan.registerDefault("fluidsynth_reverb_damping", 0);
	ConfMan.registerDefault("fluidsynth_reverb_width", 1);
	ConfMan.registerDefault("fluidsynth_reverb_level", 90);

	ConfMan.registerDefault("fluidsynth_misc_interpolation", "4th");
#endif
}

//
// Various macros used by the command line parser.
//

#ifndef DISABLE_COMMAND_LINE

// Use this for options which have an *optional* value
#define DO_OPTION_OPT(shortCmd, longCmd, defaultVal) \
	if (isLongCmd ? (!strcmp(s+2, longCmd) || !memcmp(s+2, longCmd"=", sizeof(longCmd"=") - 1)) : (tolower(s[1]) == shortCmd)) { \
		s += 2; \
		if (isLongCmd) { \
			s += sizeof(longCmd) - 1; \
			if (*s == '=') \
				s++; \
		} \
		const char *option = s; \
		if (*s == '\0' && !isLongCmd) { option = s2; i++; } \
		if (!option || *option == '\0') option = defaultVal; \
		if (option) settings[longCmd] = option;

// Use this for options which have a required (string) value
#define DO_OPTION(shortCmd, longCmd) \
	DO_OPTION_OPT(shortCmd, longCmd, 0) \
	if (!option) usage("Option '%s' requires an argument", argv[isLongCmd ? i : i-1]);

// Use this for options which have a required integer value
// (we don't check ERANGE because WinCE doesn't support errno, so we're stuck just rejecting LONG_MAX/LONG_MIN..)
#define DO_OPTION_INT(shortCmd, longCmd) \
	DO_OPTION(shortCmd, longCmd) \
	char *endptr; \
	long int retval = strtol(option, &endptr, 0); \
	if (*endptr != '\0' || retval == LONG_MAX || retval == LONG_MIN) \
		usage("--%s: Invalid number '%s'", longCmd, option);

// Use this for boolean options; this distinguishes between "-x" and "-X",
// resp. between "--some-option" and "--no-some-option".
#define DO_OPTION_BOOL(shortCmd, longCmd) \
	if (isLongCmd ? (!strcmp(s+2, longCmd) || !strcmp(s+2, "no-" longCmd)) : (tolower(s[1]) == shortCmd)) { \
		bool boolValue = (Common::isLower(s[1]) != 0); \
		s += 2; \
		if (isLongCmd) { \
			boolValue = !strcmp(s, longCmd); \
			s += boolValue ? (sizeof(longCmd) - 1) : (sizeof("no-" longCmd) - 1); \
		} \
		if (*s != '\0') goto unknownOption; \
		const char *option = boolValue ? "true" : "false"; \
		settings[longCmd] = option;

// Use this for options which never have a value, i.e. for 'commands', like "--help".
#define DO_COMMAND(shortCmd, longCmd) \
	if (isLongCmd ? (!strcmp(s+2, longCmd)) : (tolower(s[1]) == shortCmd)) { \
		s += 2; \
		if (isLongCmd) \
			s += sizeof(longCmd) - 1; \
		if (*s != '\0') goto unknownOption; \
		return longCmd;


#define DO_LONG_OPTION_OPT(longCmd, d)  DO_OPTION_OPT(0, longCmd, d)
#define DO_LONG_OPTION(longCmd)         DO_OPTION(0, longCmd)
#define DO_LONG_OPTION_INT(longCmd)     DO_OPTION_INT(0, longCmd)
#define DO_LONG_OPTION_BOOL(longCmd)    DO_OPTION_BOOL(0, longCmd)
#define DO_LONG_COMMAND(longCmd)        DO_COMMAND(0, longCmd)

// End an option handler
#define END_OPTION \
		continue; \
	}

// End an option handler
#define END_COMMAND \
	}


Common::String parseCommandLine(Common::StringMap &settings, int argc, const char * const *argv) {
	const char *s, *s2;

	if (!argv)
		return Common::String();

	// argv[0] contains the name of the executable.
	if (argv[0]) {
		s = strrchr(argv[0], '/');
		s_appName = s ? (s+1) : argv[0];
	}

	// We store all command line settings into a string map.

	// Iterate over all command line arguments and parse them into our string map.
	for (int i = 1; i < argc; ++i) {
		s = argv[i];
		s2 = (i < argc-1) ? argv[i+1] : 0;

		if (s[0] != '-') {
			// The argument doesn't start with a dash, so it's not an option.
			// Hence it must be the target name. We currently enforce that
			// this always comes last.
			if (i != argc - 1)
				usage("Stray argument '%s'", s);

			// We defer checking whether this is a valid target to a later point.
			return s;
		} else {
			// On MacOS X prior to 10.9 the OS is sometimes adding a -psn_X_XXXXXX argument (where X are digits)
			// to pass the process serial number. We need to ignore it to avoid an error.
			// When using XCode it also adds -NSDocumentRevisionsDebugMode YES argument if XCode option
			// "Allow debugging when using document Versions Browser" is on (which is the default).
#ifdef MACOSX
			if (strncmp(s, "-psn_", 5) == 0)
				continue;
			if (strcmp(s, "-NSDocumentRevisionsDebugMode") == 0) {
				++i; // Also skip the YES that follows
				continue;
			}
#endif

			bool isLongCmd = (s[0] == '-' && s[1] == '-');

			DO_COMMAND('h', "help")
			END_COMMAND

			DO_COMMAND('v', "version")
			END_COMMAND

			DO_COMMAND('t', "list-targets")
			END_COMMAND

			DO_COMMAND('z', "list-games")
			END_COMMAND

			DO_COMMAND('a', "add")
			END_COMMAND

			DO_LONG_COMMAND("detect")
			END_COMMAND

			DO_LONG_COMMAND("auto-detect")
			END_COMMAND

#ifdef DETECTOR_TESTING_HACK
			// HACK FIXME TODO: This command is intentionally *not* documented!
			DO_LONG_COMMAND("test-detector")
			END_COMMAND
#endif

#ifdef UPGRADE_ALL_TARGETS_HACK
			// HACK FIXME TODO: This command is intentionally *not* documented!
			DO_LONG_COMMAND("upgrade-targets")
			END_COMMAND
#endif

			DO_LONG_OPTION("list-saves")
				// FIXME: Need to document this.
				// TODO: Make the argument optional. If no argument is given, list all saved games
				// for all configured targets.
				return "list-saves";
			END_OPTION

			DO_OPTION('c', "config")
			END_OPTION

			DO_OPTION_INT('b', "boot-param")
			END_OPTION

			DO_OPTION_OPT('d', "debuglevel", "0")
			END_OPTION

			DO_LONG_OPTION("debugflags")
			END_OPTION

			DO_LONG_OPTION_BOOL("debug-channels-only")
			END_OPTION

			DO_OPTION('e', "music-driver")
			END_OPTION

			DO_LONG_COMMAND("list-audio-devices")
			END_COMMAND

			DO_LONG_OPTION_INT("output-rate")
			END_OPTION

			DO_OPTION_BOOL('f', "fullscreen")
			END_OPTION

			DO_LONG_OPTION_BOOL("filtering")
			END_OPTION

#ifdef ENABLE_EVENTRECORDER
			DO_LONG_OPTION_INT("disable-display")
			END_OPTION

			DO_LONG_OPTION("record-mode")
			END_OPTION

			DO_LONG_OPTION("record-file-name")
			END_OPTION
#endif

			DO_LONG_OPTION("opl-driver")
			END_OPTION

			DO_OPTION('g', "gfx-mode")
			END_OPTION

			DO_OPTION_INT('m', "music-volume")
			END_OPTION

			DO_OPTION_BOOL('n', "subtitles")
			END_OPTION

			DO_OPTION('p', "path")
				Common::FSNode path(option);
				if (!path.exists()) {
					usage("Non-existent game path '%s'", option);
				} else if (!path.isReadable()) {
					usage("Non-readable game path '%s'", option);
				}
			END_OPTION

			DO_OPTION('q', "language")
				if (Common::parseLanguage(option) == Common::UNK_LANG)
					usage("Unrecognized language '%s'", option);
			END_OPTION

			DO_OPTION_INT('s', "sfx-volume")
			END_OPTION

			DO_OPTION_INT('r', "speech-volume")
			END_OPTION

			DO_LONG_OPTION_INT("midi-gain")
			END_OPTION

			DO_OPTION_BOOL('u', "dump-scripts")
			END_OPTION

			DO_OPTION_OPT('x', "save-slot", "0")
			END_OPTION

			DO_LONG_OPTION_INT("cdrom")
			END_OPTION

			DO_LONG_OPTION_OPT("joystick", "0")
				settings["joystick_num"] = option;
				settings.erase("joystick");
			END_OPTION

			DO_LONG_OPTION("platform")
				int platform = Common::parsePlatform(option);
				if (platform == Common::kPlatformUnknown)
					usage("Unrecognized platform '%s'", option);
			END_OPTION

			DO_LONG_OPTION("soundfont")
				Common::FSNode path(option);
				if (!path.exists()) {
					usage("Non-existent soundfont path '%s'", option);
				} else if (!path.isReadable()) {
					usage("Non-readable soundfont path '%s'", option);
				}
			END_OPTION

			DO_LONG_OPTION_BOOL("disable-sdl-parachute")
			END_OPTION

			DO_LONG_OPTION_BOOL("multi-midi")
			END_OPTION

			DO_LONG_OPTION_BOOL("native-mt32")
			END_OPTION

			DO_LONG_OPTION_BOOL("enable-gs")
			END_OPTION

			DO_LONG_OPTION_BOOL("aspect-ratio")
			END_OPTION

			DO_LONG_OPTION("render-mode")
				int renderMode = Common::parseRenderMode(option);
				if (renderMode == Common::kRenderDefault)
					usage("Unrecognized render mode '%s'", option);
			END_OPTION

			DO_LONG_OPTION("savepath")
				Common::FSNode path(option);
				if (!path.exists()) {
					usage("Non-existent saved games path '%s'", option);
				} else if (!path.isWritable()) {
					usage("Non-writable saved games path '%s'", option);
				}
			END_OPTION

			DO_LONG_OPTION("extrapath")
				Common::FSNode path(option);
				if (!path.exists()) {
					usage("Non-existent extra path '%s'", option);
				} else if (!path.isReadable()) {
					usage("Non-readable extra path '%s'", option);
				}
			END_OPTION

			DO_LONG_OPTION_INT("talkspeed")
			END_OPTION

			DO_LONG_OPTION_BOOL("copy-protection")
			END_OPTION

			DO_LONG_OPTION("gui-theme")
			END_OPTION

			DO_LONG_OPTION("game")
			END_OPTION

			DO_LONG_OPTION_BOOL("recursive")
			END_OPTION

			DO_LONG_OPTION("themepath")
				Common::FSNode path(option);
				if (!path.exists()) {
					usage("Non-existent theme path '%s'", option);
				} else if (!path.isReadable()) {
					usage("Non-readable theme path '%s'", option);
				}
			END_OPTION

			DO_LONG_COMMAND("list-themes")
			END_COMMAND

			DO_LONG_OPTION("target-md5")
			END_OPTION

#ifdef ENABLE_SCUMM
			DO_LONG_OPTION_INT("tempo")
			END_OPTION
#ifdef ENABLE_SCUMM_7_8
			DO_LONG_OPTION_INT("dimuse-tempo")
			END_OPTION
#endif
#endif
#if defined(ENABLE_SCUMM) || defined(ENABLE_GROOVIE)
			DO_LONG_OPTION_BOOL("demo-mode")
			END_OPTION
#endif

#if defined(ENABLE_SKY) || defined(ENABLE_QUEEN)
			DO_LONG_OPTION_BOOL("alt-intro")
			END_OPTION
#endif

#ifdef IPHONE
			// This is automatically set when launched from the Springboard.
			DO_LONG_OPTION_OPT("launchedFromSB", 0)
			END_OPTION
#endif

#if defined(WIN32) && !defined(_WIN32_WCE) && !defined(__SYMBIAN32__)
			// Optional console window on Windows (default: enabled)
			DO_LONG_OPTION_BOOL("console")
			END_OPTION
#endif

#if defined(ENABLE_DIRECTOR)
			DO_LONG_OPTION("start-movie")
			END_OPTION
#endif

unknownOption:
			// If we get till here, the option is unhandled and hence unknown.
			usage("Unrecognized option '%s'", argv[i]);
		}
	}

	return Common::String();
}

/** List all supported game IDs, i.e. all games which any loaded plugin supports. */
static void listGames() {
	printf("Game ID              Full Title                                            \n"
	       "-------------------- ------------------------------------------------------\n");

	const PluginList &plugins = EngineMan.getPlugins();
	for (PluginList::const_iterator iter = plugins.begin(); iter != plugins.end(); ++iter) {
		GameList list = (*iter)->get<MetaEngine>().getSupportedGames();
		for (GameList::iterator v = list.begin(); v != list.end(); ++v) {
			printf("%-20s %s\n", v->gameid().c_str(), v->description().c_str());
		}
	}
}

/** List all targets which are configured in the config file. */
static void listTargets() {
	printf("Target               Description                                           \n"
	       "-------------------- ------------------------------------------------------\n");

	using namespace Common;
	const ConfigManager::DomainMap &domains = ConfMan.getGameDomains();
	ConfigManager::DomainMap::const_iterator iter;

	Common::Array<Common::String> targets;
	targets.reserve(domains.size());

	for (iter = domains.begin(); iter != domains.end(); ++iter) {
		Common::String name(iter->_key);
		Common::String description(iter->_value.getVal("description"));

		if (description.empty()) {
			// FIXME: At this point, we should check for a "gameid" override
			// to find the proper desc. In fact, the platform probably should
			// be taken into account, too.
			Common::String gameid(name);
			GameDescriptor g = EngineMan.findGame(gameid);
			if (g.description().size() > 0)
				description = g.description();
		}

		targets.push_back(Common::String::format("%-20s %s", name.c_str(), description.c_str()));
	}

	Common::sort(targets.begin(), targets.end());

	for (Common::Array<Common::String>::const_iterator i = targets.begin(), end = targets.end(); i != end; ++i)
		printf("%s\n", i->c_str());
}

/** List all saves states for the given target. */
static Common::Error listSaves(const char *target) {
	Common::Error result = Common::kNoError;

	// FIXME HACK
	g_system->initBackend();

	// Grab the "target" domain, if any
	const Common::ConfigManager::Domain *domain = ConfMan.getDomain(target);

	// Set up the game domain as newly active domain, so
	// target specific savepath will be checked
	Common::String oldDomain = ConfMan.getActiveDomainName();
	ConfMan.setActiveDomain(target);

	// Grab the gameid from the domain resp. use the target as gameid
	Common::String gameid;
	if (domain)
		gameid = domain->getVal("gameid");
	if (gameid.empty())
		gameid = target;
	gameid.toLowercase();	// Normalize it to lower case

	// Find the plugin that will handle the specified gameid
	const Plugin *plugin = nullptr;
	GameDescriptor game = EngineMan.findGame(gameid, &plugin);

	if (!plugin) {
		return Common::Error(Common::kEnginePluginNotFound,
						Common::String::format("target '%s', gameid '%s", target, gameid.c_str()));
	}

	const MetaEngine &metaEngine = plugin->get<MetaEngine>();

	if (!metaEngine.hasFeature(MetaEngine::kSupportsListSaves)) {
		// TODO: Include more info about the target (desc, engine name, ...) ???
		return Common::Error(Common::kEnginePluginNotSupportSaves,
						Common::String::format("target '%s', gameid '%s", target, gameid.c_str()));
	} else {
		// Query the plugin for a list of saved games
		SaveStateList saveList = metaEngine.listSaves(target);

		if (saveList.size() > 0) {
			// TODO: Include more info about the target (desc, engine name, ...) ???
			printf("Save states for target '%s' (gameid '%s'):\n", target, gameid.c_str());
			printf("  Slot Description                                           \n"
				   "  ---- ------------------------------------------------------\n");

			for (SaveStateList::const_iterator x = saveList.begin(); x != saveList.end(); ++x) {
				printf("  %-4d %s\n", x->getSaveSlot(), x->getDescription().c_str());
				// TODO: Could also iterate over the full hashmap, printing all key-value pairs
			}
		} else {
			printf("There are no save states for target '%s' (gameid '%s'):\n", target, gameid.c_str());
		}
	}

	// Revert to the old active domain
	ConfMan.setActiveDomain(oldDomain);

	return result;
}

/** Lists all usable themes */
static void listThemes() {
	typedef Common::List<GUI::ThemeEngine::ThemeDescriptor> ThList;
	ThList thList;
	GUI::ThemeEngine::listUsableThemes(thList);

	printf("Theme          Description\n");
	printf("-------------- ------------------------------------------------\n");

	for (ThList::const_iterator i = thList.begin(); i != thList.end(); ++i)
		printf("%-14s %s\n", i->id.c_str(), i->name.c_str());
}

/** Lists all output devices */
static void listAudioDevices() {
	PluginList pluginList = MusicMan.getPlugins();

	printf("ID                             Description\n");
	printf("------------------------------ ------------------------------------------------\n");

	for (PluginList::const_iterator i = pluginList.begin(), iend = pluginList.end(); i != iend; ++i) {
		const MusicPluginObject &musicObject = (*i)->get<MusicPluginObject>();
		MusicDevices deviceList = musicObject.getDevices();
		for (MusicDevices::iterator j = deviceList.begin(), jend = deviceList.end(); j != jend; ++j) {
			printf("%-30s %s\n", Common::String::format("\"%s\"", j->getCompleteId().c_str()).c_str(), j->getCompleteName().c_str());
		}
	}
}

/** Display all games in the given directory, or current directory if empty */
static GameList getGameList(const Common::FSNode &dir) {
	Common::FSList files;

	//Collect all files from directory
	if (!dir.getChildren(files, Common::FSNode::kListAll)) {
		printf("Path %s does not exist or is not a directory.\n", dir.getPath().c_str());
		return GameList();
	}

	// detect Games
	GameList candidates(EngineMan.detectGames(files));
	Common::String dataPath = dir.getPath();
	// add game data path
	for (GameList::iterator v = candidates.begin(); v != candidates.end(); ++v) {
		(*v)["path"] = dataPath;
	}
	return candidates;
}

static bool addGameToConf(const GameDescriptor &gd) {
	const Common::String &domain = gd.preferredtarget();

	// If game has already been added, don't add
	if (ConfMan.hasGameDomain(domain))
		return false;

	// Add the name domain
	ConfMan.addGameDomain(domain);

	// Copy all non-empty key/value pairs into the new domain
	for (GameDescriptor::const_iterator iter = gd.begin(); iter != gd.end(); ++iter) {
		if (!iter->_value.empty() && iter->_key != "preferredtarget")
			ConfMan.set(iter->_key, iter->_value, domain);
	}

	// Display added game info
	printf("Game Added: \n  GameID:   %s\n  Name:     %s\n  Language: %s\n  Platform: %s\n",
			gd.gameid().c_str(),
			gd.description().c_str(),
			Common::getLanguageDescription(gd.language()),
			Common::getPlatformDescription(gd.platform()));

	return true;
}

static GameList recListGames(const Common::FSNode &dir, const Common::String &gameId, bool recursive) {
	GameList list = getGameList(dir);

	if (recursive) {
		Common::FSList files;
		dir.getChildren(files, Common::FSNode::kListDirectoriesOnly);
		for (Common::FSList::const_iterator file = files.begin(); file != files.end(); ++file) {
			GameList rec = recListGames(*file, gameId, recursive);
			for (GameList::const_iterator game = rec.begin(); game != rec.end(); ++game) {
				if (gameId.empty() || game->gameid().c_str() == gameId)
					list.push_back(*game);
			}
		}
	}

	return list;
}

/** Display all games in the given directory, return ID of first detected game */
static Common::String detectGames(const Common::String &path, const Common::String &gameId, bool recursive) {
	bool noPath = path.empty();
	//Current directory
	Common::FSNode dir(path);
	GameList candidates = recListGames(dir, gameId, recursive);

	if (candidates.empty()) {
		printf("WARNING: ScummVM could not find any game in %s\n", dir.getPath().c_str());
		if (noPath) {
			printf("WARNING: Consider using --path=<path> *before* --add or --detect to specify a directory\n");
		}
		if (!recursive) {
			printf("WARNING: Consider using --recursive *before* --add or --detect to search inside subdirectories\n");
		}
		return Common::String();
	}
	// TODO this is not especially pretty
	printf("ID             Description                                                Full Path\n");
	printf("-------------- ---------------------------------------------------------- ---------------------------------------------------------\n");
	for (GameList::iterator v = candidates.begin(); v != candidates.end(); ++v) {
		printf("%-14s %-58s %s\n", v->gameid().c_str(), v->description().c_str(), (*v)["path"].c_str());
	}

	return candidates[0].gameid();
}

static int recAddGames(const Common::FSNode &dir, const Common::String &game, bool recursive) {
	int count = 0;
	GameList list = getGameList(dir);
	for (GameList::iterator v = list.begin(); v != list.end(); ++v) {
		if (v->gameid().c_str() != game && !game.empty()) {
			printf("Found %s, only adding %s per --game option, ignoring...\n", v->gameid().c_str(), game.c_str());
		} else if (!addGameToConf(*v)) {
			// TODO Is it reall the case that !addGameToConf iff already added?
			printf("Found %s, but has already been added, skipping\n", v->gameid().c_str());
		} else {
			printf("Found %s, adding...\n", v->gameid().c_str());
			count++;
		}
	}

	if (recursive) {
		Common::FSList files;
		if (dir.getChildren(files, Common::FSNode::kListDirectoriesOnly)) {
			for (Common::FSList::const_iterator file = files.begin(); file != files.end(); ++file) {
				count += recAddGames(*file, game, recursive);
			}
		}
	}

	return count;
}

static bool addGames(const Common::String &path, const Common::String &game, bool recursive) {
	//Current directory
	Common::FSNode dir(path);
	int added = recAddGames(dir, game, recursive);
	printf("Added %d games\n", added);
	if (added == 0 && !recursive) {
		printf("Consider using --recursive to search inside subdirectories\n");
	}
	ConfMan.flushToDisk();
	return true;
}

#ifdef DETECTOR_TESTING_HACK
static void runDetectorTest() {
	// HACK: The following code can be used to test the detection code of our
	// engines. Basically, it loops over all targets, and calls the detector
	// for the given path. It then prints out the result and also checks
	// whether the result agrees with the settings of the target.

	const Common::ConfigManager::DomainMap &domains = ConfMan.getGameDomains();
	Common::ConfigManager::DomainMap::const_iterator iter = domains.begin();
	int success = 0, failure = 0;
	for (iter = domains.begin(); iter != domains.end(); ++iter) {
		Common::String name(iter->_key);
		Common::String gameid(iter->_value.getVal("gameid"));
		Common::String path(iter->_value.getVal("path"));
		printf("Looking at target '%s', gameid '%s', path '%s' ...\n",
				name.c_str(), gameid.c_str(), path.c_str());
		if (path.empty()) {
			printf(" ... no path specified, skipping\n");
			continue;
		}
		if (gameid.empty()) {
			gameid = name;
		}

		Common::FSNode dir(path);
		Common::FSList files;
		if (!dir.getChildren(files, Common::FSNode::kListAll)) {
			printf(" ... invalid path, skipping\n");
			continue;
		}

		GameList candidates(EngineMan.detectGames(files));
		bool gameidDiffers = false;
		GameList::iterator x;
		for (x = candidates.begin(); x != candidates.end(); ++x) {
			gameidDiffers |= (scumm_stricmp(gameid.c_str(), x->gameid().c_str()) != 0);
		}

		if (candidates.empty()) {
			printf(" FAILURE: No games detected\n");
			failure++;
		} else if (candidates.size() > 1) {
			if (gameidDiffers) {
				printf(" WARNING: Multiple games detected, some/all with wrong gameid\n");
			} else {
				printf(" WARNING: Multiple games detected, but all have matching gameid\n");
			}
			failure++;
		} else if (gameidDiffers) {
			printf(" FAILURE: Wrong gameid detected\n");
			failure++;
		} else {
			printf(" SUCCESS: Game was detected correctly\n");
			success++;
		}

		for (x = candidates.begin(); x != candidates.end(); ++x) {
			printf("    gameid '%s', desc '%s', language '%s', platform '%s'\n",
				   x->gameid().c_str(),
				   x->description().c_str(),
				   Common::getLanguageCode(x->language()),
				   Common::getPlatformCode(x->platform()));
		}
	}
	int total = domains.size();
	printf("Detector test run: %d fail, %d success, %d skipped, out of %d\n",
			failure, success, total - failure - success, total);
}
#endif

#ifdef UPGRADE_ALL_TARGETS_HACK
void upgradeTargets() {
	// HACK: The following upgrades all your targets to the latest and
	// greatest. Right now that means updating the guioptions and (optionally)
	// also the game descriptions.
	// Basically, it loops over all targets, and calls the detector for the
	// given path. It then compares the result with the settings of the target.
	// If the basics seem to match, it updates the guioptions.

	printf("Upgrading all your existing targets\n");

	Common::ConfigManager::DomainMap::iterator iter = ConfMan.beginGameDomains();
	for (; iter != ConfMan.endGameDomains(); ++iter) {
		Common::ConfigManager::Domain &dom = iter->_value;
		Common::String name(iter->_key);
		Common::String gameid(dom.getVal("gameid"));
		Common::String path(dom.getVal("path"));
		printf("Looking at target '%s', gameid '%s' ...\n",
				name.c_str(), gameid.c_str());
		if (path.empty()) {
			printf(" ... no path specified, skipping\n");
			continue;
		}
		if (gameid.empty()) {
			gameid = name;
		}
		gameid.toLowercase();	// TODO: Is this paranoia? Maybe we should just assume all lowercase, always?

		Common::FSNode dir(path);
		Common::FSList files;
		if (!dir.getChildren(files, Common::FSNode::kListAll)) {
			printf(" ... invalid path, skipping\n");
			continue;
		}

		Common::Language lang = Common::parseLanguage(dom.getVal("language"));
		Common::Platform plat = Common::parsePlatform(dom.getVal("platform"));
		Common::String desc(dom.getVal("description"));

		GameList candidates(EngineMan.detectGames(files));
		GameDescriptor *g = 0;

		// We proceed as follows:
		// * If detection failed to produce candidates, skip.
		// * If there is a unique detector match, trust it.
		// * If there are multiple match, run over them comparing gameid, language and platform.
		//   If we end up with a unique match, use it. Otherwise, skip.
		if (candidates.size() == 0) {
			printf(" ... failed to detect game, skipping\n");
			continue;
		}
		if (candidates.size() > 1) {
			// Scan over all candidates, check if there is a unique match for gameid, language and platform
			GameList::iterator x;
			int matchesFound = 0;
			for (x = candidates.begin(); x != candidates.end(); ++x) {
				if (x->gameid() == gameid && x->language() == lang && x->platform() == plat) {
					matchesFound++;
					g = &(*x);
				}
			}
			if (matchesFound != 1) {
				printf(" ... detected multiple games, could not establish unique match, skipping\n");
				continue;
			}
		} else {
			// Unique match -> use it
			g = &candidates[0];
		}

		// At this point, g points to a GameDescriptor which we can use to update
		// the target referred to by dom. We update several things

		// Always set the gameid explicitly (in case of legacy targets)
		dom["gameid"] = g->gameid();

		// Always set the GUI options. The user should not modify them, and engines might
		// gain more features over time, so we want to keep this list up-to-date.
		if (g->contains("guioptions")) {
			printf("  -> update guioptions to '%s'\n", (*g)["guioptions"].c_str());
			dom["guioptions"] = (*g)["guioptions"];
		} else if (dom.contains("guioptions")) {
			dom.erase("guioptions");
		}

		// Update the language setting but only if none has been set yet.
		if (lang == Common::UNK_LANG && g->language() != Common::UNK_LANG) {
			printf("  -> set language to '%s'\n", Common::getLanguageCode(g->language()));
			dom["language"] = (*g)["language"];
		}

		// Update the platform setting but only if none has been set yet.
		if (plat == Common::kPlatformUnknown && g->platform() != Common::kPlatformUnknown) {
			printf("  -> set platform to '%s'\n", Common::getPlatformCode(g->platform()));
			dom["platform"] = (*g)["platform"];
		}

		// TODO: We could also update the description. But not everybody will want that.
		// Esp. because for some games (e.g. the combined Zak/Loom FM-TOWNS demo etc.)
		// ScummVM still generates an incorrect description string. So, the description
		// should only be updated if the user explicitly requests this.
#if 0
		if (desc != g->description()) {
			printf("  -> update desc from '%s' to\n                      '%s' ?\n", desc.c_str(), g->description().c_str());
			dom["description"] = (*g)["description"];
		}
#endif
	}

	// Finally, save our changes to disk
	ConfMan.flushToDisk();
}
#endif

#else // DISABLE_COMMAND_LINE


Common::String parseCommandLine(Common::StringMap &settings, int argc, const char * const *argv) {
	return Common::String();
}


#endif // DISABLE_COMMAND_LINE


bool processSettings(Common::String &command, Common::StringMap &settings, Common::Error &err) {
	err = Common::kNoError;

#ifndef DISABLE_COMMAND_LINE

	// Handle commands passed via the command line (like --list-targets and
	// --list-games). This must be done after the config file and the plugins
	// have been loaded.
	if (command == "list-targets") {
		listTargets();
		return true;
	} else if (command == "list-games") {
		listGames();
		return true;
	} else if (command == "list-saves") {
		err = listSaves(settings["list-saves"].c_str());
		return true;
	} else if (command == "list-themes") {
		listThemes();
		return true;
	} else if (command == "list-audio-devices") {
		listAudioDevices();
		return true;
	} else if (command == "version") {
		printf("%s\n", gScummVMFullVersion);
		printf("Features compiled in: %s\n", gScummVMFeatures);
		return true;
	} else if (command == "help") {
		printf(HELP_STRING, s_appName);
		return true;
	} else if (command == "auto-detect") {
		bool resursive = settings["recursive"] == "true";
		// If auto-detects fails (returns an empty ID) return true to close ScummVM.
		// If we get a non-empty ID, we store it in command so that it gets processed together with the
		// other command line options below.
		if (resursive) {
			printf("ERROR: Autodetection not supported with --recursive; are you sure you didn't want --detect?\n");
			err = Common::kUnknownError;
			return true;
			// There is not a particularly good technical reason for this.
			// From an UX point of view, however, it might get confusing.
			// Consider removing this if consensus says otherwise.
		} else {
			command = detectGames(settings["path"], settings["game"], resursive);
			if (command.empty()) {
				err = Common::kNoGameDataFoundError;
				return true;
			}
		}
	} else if (command == "detect") {
		detectGames(settings["path"], settings["game"], settings["recursive"] == "true");
		return true;
	} else if (command == "add") {
		addGames(settings["path"], settings["game"], settings["recursive"] == "true");
		return true;
	}
#ifdef DETECTOR_TESTING_HACK
	else if (command == "test-detector") {
		runDetectorTest();
		return true;
	}
#endif
#ifdef UPGRADE_ALL_TARGETS_HACK
	else if (command == "upgrade-targets") {
		upgradeTargets();
		return true;
	}
#endif

#endif // DISABLE_COMMAND_LINE


	// If a target was specified, check whether there is either a game
	// domain (i.e. a target) matching this argument, or alternatively
	// whether there is a gameid matching that name.
	if (!command.empty()) {
		GameDescriptor gd = EngineMan.findGame(command);
		if (ConfMan.hasGameDomain(command) || !gd.gameid().empty()) {
			bool idCameFromCommandLine = false;

			// WORKAROUND: Fix for bug #1719463: "DETECTOR: Launching
			// undefined target adds launcher entry"
			//
			// We designate gameids which come strictly from command line
			// so AdvancedDetector will not save config file with invalid
			// gameid in case target autoupgrade was performed
			if (!ConfMan.hasGameDomain(command)) {
				idCameFromCommandLine = true;
			}

			ConfMan.setActiveDomain(command);

			if (idCameFromCommandLine)
				ConfMan.set("id_came_from_command_line", "1");

		} else {
#ifndef DISABLE_COMMAND_LINE
			usage("Unrecognized game target '%s'", command.c_str());
#endif // DISABLE_COMMAND_LINE
		}
	}


	// Finally, store the command line settings into the config manager.
	for (Common::StringMap::const_iterator x = settings.begin(); x != settings.end(); ++x) {
		Common::String key(x->_key);
		Common::String value(x->_value);

		// Replace any "-" in the key by "_" (e.g. change "save-slot" to "save_slot").
		for (Common::String::iterator c = key.begin(); c != key.end(); ++c)
			if (*c == '-')
				*c = '_';

		// Store it into ConfMan.
		ConfMan.set(key, value, Common::ConfigManager::kTransientDomain);
	}

	return false;
}

} // End of namespace Base