fixed some smaller issues with loading custom artwork
[rocksndiamonds.git] / src / libgame / misc.c
1 // ============================================================================
2 // Artsoft Retro-Game Library
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
5 //                  Holger Schemel
6 //                  info@artsoft.org
7 //                  http://www.artsoft.org/
8 // ----------------------------------------------------------------------------
9 // misc.c
10 // ============================================================================
11
12 #include <time.h>
13 #include <sys/time.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16 #include <stdarg.h>
17 #include <ctype.h>
18 #include <string.h>
19 #include <unistd.h>
20 #include <errno.h>
21
22 #include "platform.h"
23
24 #if !defined(PLATFORM_WIN32)
25 #include <pwd.h>
26 #include <sys/param.h>
27 #endif
28
29 #include "misc.h"
30 #include "setup.h"
31 #include "random.h"
32 #include "text.h"
33 #include "image.h"
34
35
36 /* ========================================================================= */
37 /* some generic helper functions                                             */
38 /* ========================================================================= */
39
40 /* ------------------------------------------------------------------------- */
41 /* platform independent wrappers for printf() et al. (newline aware)         */
42 /* ------------------------------------------------------------------------- */
43
44 #if defined(PLATFORM_ANDROID)
45 static int android_log_prio = ANDROID_LOG_INFO;
46 #endif
47
48 #if 0
49 static void vfPrintLog(FILE *stream, char *format, va_list ap)
50 {
51 }
52
53 static void vfPrintLog(FILE *stream, char *format, va_list ap)
54 {
55 }
56
57 static void fPrintLog(FILE *stream, char *format, va_list ap)
58 {
59 }
60
61 static void fPrintLog(FILE *stream, char *format, va_list ap)
62 {
63 }
64 #endif
65
66 static void vfprintf_nonewline(FILE *stream, char *format, va_list ap)
67 {
68 #if defined(PLATFORM_ANDROID)
69   // (prefix text of logging output is currently skipped on Android)
70   //__android_log_vprint(android_log_prio, program.program_title, format, ap);
71 #else
72   va_list ap2;
73   va_copy(ap2, ap);
74
75   vfprintf(stream, format, ap);
76   vfprintf(stderr, format, ap2);
77
78   va_end(ap2);
79 #endif
80 }
81
82 static void vfprintf_newline(FILE *stream, char *format, va_list ap)
83 {
84 #if defined(PLATFORM_ANDROID)
85   __android_log_vprint(android_log_prio, program.program_title, format, ap);
86 #else
87   char *newline = STRING_NEWLINE;
88
89   va_list ap2;
90   va_copy(ap2, ap);
91
92   vfprintf(stream, format, ap);
93   fprintf(stream, "%s", newline);
94
95   vfprintf(stderr, format, ap2);
96   fprintf(stderr, "%s", newline);
97
98   va_end(ap2);
99 #endif
100 }
101
102 static void fprintf_nonewline(FILE *stream, char *format, ...)
103 {
104   va_list ap;
105
106   va_start(ap, format);
107   vfprintf_nonewline(stream, format, ap);
108   va_end(ap);
109 }
110
111 static void fprintf_newline(FILE *stream, char *format, ...)
112 {
113   va_list ap;
114
115   va_start(ap, format);
116   vfprintf_newline(stream, format, ap);
117   va_end(ap);
118 }
119
120 void fprintf_line(FILE *stream, char *line_chars, int line_length)
121 {
122   int i;
123
124   for (i = 0; i < line_length; i++)
125     fprintf_nonewline(stream, "%s", line_chars);
126
127   fprintf_newline(stream, "");
128 }
129
130 void printf_line(char *line_chars, int line_length)
131 {
132   fprintf_line(stdout, line_chars, line_length);
133 }
134
135 void printf_line_with_prefix(char *prefix, char *line_chars, int line_length)
136 {
137   fprintf(stdout, "%s", prefix);
138   fprintf_line(stdout, line_chars, line_length);
139 }
140
141
142 /* ------------------------------------------------------------------------- */
143 /* string functions                                                          */
144 /* ------------------------------------------------------------------------- */
145
146 /* int2str() returns a number converted to a string;
147    the used memory is static, but will be overwritten by later calls,
148    so if you want to save the result, copy it to a private string buffer;
149    there can be 10 local calls of int2str() without buffering the result --
150    the 11th call will then destroy the result from the first call and so on.
151 */
152
153 char *int2str(int number, int size)
154 {
155   static char shift_array[10][40];
156   static int shift_counter = 0;
157   char *s = shift_array[shift_counter];
158
159   shift_counter = (shift_counter + 1) % 10;
160
161   if (size > 20)
162     size = 20;
163
164   if (size > 0)
165   {
166     sprintf(s, "                    %09d", number);
167     return &s[strlen(s) - size];
168   }
169   else
170   {
171     sprintf(s, "%d", number);
172     return s;
173   }
174 }
175
176
177 /* something similar to "int2str()" above, but allocates its own memory
178    and has a different interface; we cannot use "itoa()", because this
179    seems to be already defined when cross-compiling to the win32 target */
180
181 char *i_to_a(unsigned int i)
182 {
183   static char *a = NULL;
184
185   checked_free(a);
186
187   if (i > 2147483647)   /* yes, this is a kludge */
188     i = 2147483647;
189
190   a = checked_malloc(10 + 1);
191
192   sprintf(a, "%d", i);
193
194   return a;
195 }
196
197
198 /* calculate base-2 logarithm of argument (rounded down to integer;
199    this function returns the number of the highest bit set in argument) */
200
201 int log_2(unsigned int x)
202 {
203   int e = 0;
204
205   while ((1 << e) < x)
206   {
207     x -= (1 << e);      /* for rounding down (rounding up: remove this line) */
208     e++;
209   }
210
211   return e;
212 }
213
214 boolean getTokenValueFromString(char *string, char **token, char **value)
215 {
216   return getTokenValueFromSetupLine(string, token, value);
217 }
218
219
220 /* ------------------------------------------------------------------------- */
221 /* counter functions                                                         */
222 /* ------------------------------------------------------------------------- */
223
224 /* maximal allowed length of a command line option */
225 #define MAX_OPTION_LEN          256
226
227 static unsigned int getCurrentMS()
228 {
229   return SDL_GetTicks();
230 }
231
232 static unsigned int mainCounter(int mode)
233 {
234   static unsigned int base_ms = 0;
235   unsigned int current_ms;
236
237   /* get current system milliseconds */
238   current_ms = getCurrentMS();
239
240   /* reset base timestamp in case of counter reset or wrap-around */
241   if (mode == INIT_COUNTER || current_ms < base_ms)
242     base_ms = current_ms;
243
244   /* return milliseconds since last counter reset */
245   return current_ms - base_ms;
246 }
247
248 void InitCounter()              /* set counter back to zero */
249 {
250   mainCounter(INIT_COUNTER);
251 }
252
253 unsigned int Counter()  /* get milliseconds since last call of InitCounter() */
254 {
255   return mainCounter(READ_COUNTER);
256 }
257
258 static void sleep_milliseconds(unsigned int milliseconds_delay)
259 {
260   boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
261
262   if (do_busy_waiting)
263   {
264     /* we want to wait only a few ms -- if we assume that we have a
265        kernel timer resolution of 10 ms, we would wait far to long;
266        therefore it's better to do a short interval of busy waiting
267        to get our sleeping time more accurate */
268
269     unsigned int base_counter = Counter(), actual_counter = Counter();
270
271     while (actual_counter < base_counter + milliseconds_delay &&
272            actual_counter >= base_counter)
273       actual_counter = Counter();
274   }
275   else
276   {
277     SDL_Delay(milliseconds_delay);
278   }
279 }
280
281 void Delay(unsigned int delay)  /* Sleep specified number of milliseconds */
282 {
283   sleep_milliseconds(delay);
284 }
285
286 boolean FrameReached(unsigned int *frame_counter_var,
287                      unsigned int frame_delay)
288 {
289   unsigned int actual_frame_counter = FrameCounter;
290
291   if (actual_frame_counter >= *frame_counter_var &&
292       actual_frame_counter < *frame_counter_var + frame_delay)
293     return FALSE;
294
295   *frame_counter_var = actual_frame_counter;
296
297   return TRUE;
298 }
299
300 boolean DelayReached(unsigned int *counter_var,
301                      unsigned int delay)
302 {
303   unsigned int actual_counter = Counter();
304
305   if (actual_counter >= *counter_var &&
306       actual_counter < *counter_var + delay)
307     return FALSE;
308
309   *counter_var = actual_counter;
310
311   return TRUE;
312 }
313
314 void WaitUntilDelayReached(unsigned int *counter_var, unsigned int delay)
315 {
316   unsigned int actual_counter;
317
318   while (1)
319   {
320     actual_counter = Counter();
321
322     if (actual_counter >= *counter_var &&
323         actual_counter < *counter_var + delay)
324       sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
325     else
326       break;
327   }
328
329   *counter_var = actual_counter;
330 }
331
332
333 /* ------------------------------------------------------------------------- */
334 /* random generator functions                                                */
335 /* ------------------------------------------------------------------------- */
336
337 unsigned int init_random_number(int nr, int seed)
338 {
339   if (seed == NEW_RANDOMIZE)
340   {
341     /* default random seed */
342     seed = (int)time(NULL);                     // seconds since the epoch
343
344 #if !defined(PLATFORM_WIN32)
345     /* add some more randomness */
346     struct timeval current_time;
347
348     gettimeofday(&current_time, NULL);
349
350     seed += (int)current_time.tv_usec;          // microseconds since the epoch
351 #endif
352
353     /* add some more randomness */
354     seed += (int)SDL_GetTicks();                // milliseconds since SDL init
355
356     /* add some more randomness */
357     seed += GetSimpleRandom(1000000);
358   }
359
360   srandom_linux_libc(nr, (unsigned int) seed);
361
362   return (unsigned int) seed;
363 }
364
365 unsigned int get_random_number(int nr, int max)
366 {
367   return (max > 0 ? random_linux_libc(nr) % max : 0);
368 }
369
370
371 /* ------------------------------------------------------------------------- */
372 /* system info functions                                                     */
373 /* ------------------------------------------------------------------------- */
374
375 #if !defined(PLATFORM_ANDROID)
376 static char *get_corrected_real_name(char *real_name)
377 {
378   char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
379   char *from_ptr = real_name;
380   char *to_ptr   = real_name_new;
381
382   /* copy the name string, but not more than MAX_USERNAME_LEN characters */
383   while (*from_ptr && (int)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
384   {
385     /* the name field read from "passwd" file may also contain additional
386        user information, separated by commas, which will be removed here */
387     if (*from_ptr == ',')
388       break;
389
390     /* the user's real name may contain 'german sharp s' characters,
391        which have no equivalent in upper case letters (used by our fonts) */
392     if (*from_ptr == CHAR_BYTE_SHARP_S)
393     {
394       from_ptr++;
395       *to_ptr++ = 's';
396       *to_ptr++ = 's';
397     }
398     else
399       *to_ptr++ = *from_ptr++;
400   }
401
402   *to_ptr = '\0';
403
404   return real_name_new;
405 }
406 #endif
407
408 char *getLoginName()
409 {
410   static char *login_name = NULL;
411
412 #if defined(PLATFORM_WIN32)
413   if (login_name == NULL)
414   {
415     unsigned long buffer_size = MAX_USERNAME_LEN + 1;
416     login_name = checked_malloc(buffer_size);
417
418     if (GetUserName(login_name, &buffer_size) == 0)
419       strcpy(login_name, ANONYMOUS_NAME);
420   }
421 #else
422   if (login_name == NULL)
423   {
424     struct passwd *pwd;
425
426     if ((pwd = getpwuid(getuid())) == NULL)
427       login_name = ANONYMOUS_NAME;
428     else
429       login_name = getStringCopy(pwd->pw_name);
430   }
431 #endif
432
433   return login_name;
434 }
435
436 char *getRealName()
437 {
438   static char *real_name = NULL;
439
440 #if defined(PLATFORM_WIN32)
441   if (real_name == NULL)
442   {
443     static char buffer[MAX_USERNAME_LEN + 1];
444     unsigned long buffer_size = MAX_USERNAME_LEN + 1;
445
446     if (GetUserName(buffer, &buffer_size) != 0)
447       real_name = get_corrected_real_name(buffer);
448     else
449       real_name = ANONYMOUS_NAME;
450   }
451 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
452   if (real_name == NULL)
453   {
454     struct passwd *pwd;
455
456     if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
457       real_name = get_corrected_real_name(pwd->pw_gecos);
458     else
459       real_name = ANONYMOUS_NAME;
460   }
461 #else
462   real_name = ANONYMOUS_NAME;
463 #endif
464
465   return real_name;
466 }
467
468 time_t getFileTimestampEpochSeconds(char *filename)
469 {
470   struct stat file_status;
471
472   if (stat(filename, &file_status) != 0)        /* cannot stat file */
473     return 0;
474
475   return file_status.st_mtime;
476 }
477
478
479 /* ------------------------------------------------------------------------- */
480 /* path manipulation functions                                               */
481 /* ------------------------------------------------------------------------- */
482
483 static char *getLastPathSeparatorPtr(char *filename)
484 {
485   char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
486
487   if (last_separator == NULL)   /* also try DOS/Windows variant */
488     last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
489
490   return last_separator;
491 }
492
493 char *getBaseNamePtr(char *filename)
494 {
495   char *last_separator = getLastPathSeparatorPtr(filename);
496
497   if (last_separator != NULL)
498     return last_separator + 1;  /* separator found: strip base path */
499   else
500     return filename;            /* no separator found: filename has no path */
501 }
502
503 char *getBaseName(char *filename)
504 {
505   return getStringCopy(getBaseNamePtr(filename));
506 }
507
508 char *getBasePath(char *filename)
509 {
510   char *basepath = getStringCopy(filename);
511   char *last_separator = getLastPathSeparatorPtr(basepath);
512
513   if (last_separator != NULL)
514     *last_separator = '\0';     /* separator found: strip basename */
515   else
516     basepath = ".";             /* no separator found: use current path */
517
518   return basepath;
519 }
520
521 static char *getProgramMainDataPath()
522 {
523   char *main_data_path = getStringCopy(program.command_basepath);
524
525 #if defined(PLATFORM_MACOSX)
526   static char *main_data_binary_subdir = NULL;
527
528   if (main_data_binary_subdir == NULL)
529   {
530     main_data_binary_subdir = checked_malloc(strlen(program.program_title) + 1 +
531                                              strlen("app") + 1 +
532                                              strlen(MAC_APP_BINARY_SUBDIR) + 1);
533
534     sprintf(main_data_binary_subdir, "%s.app/%s",
535             program.program_title, MAC_APP_BINARY_SUBDIR);
536   }
537
538   // cut relative path to Mac OS X application binary directory from path
539   if (strSuffix(main_data_path, main_data_binary_subdir))
540     main_data_path[strlen(main_data_path) -
541                    strlen(main_data_binary_subdir)] = '\0';
542
543   // cut trailing path separator from path (but not if path is root directory)
544   if (strSuffix(main_data_path, "/") && !strEqual(main_data_path, "/"))
545     main_data_path[strlen(main_data_path) - 1] = '\0';
546 #endif
547
548   return main_data_path;
549 }
550
551
552 /* ------------------------------------------------------------------------- */
553 /* various string functions                                                  */
554 /* ------------------------------------------------------------------------- */
555
556 char *getStringCat2WithSeparator(char *s1, char *s2, char *sep)
557 {
558   char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
559                                          strlen(s2) + 1);
560
561   sprintf(complete_string, "%s%s%s", s1, sep, s2);
562
563   return complete_string;
564 }
565
566 char *getStringCat3WithSeparator(char *s1, char *s2, char *s3, char *sep)
567 {
568   char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
569                                          strlen(s2) + strlen(sep) +
570                                          strlen(s3) + 1);
571
572   sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
573
574   return complete_string;
575 }
576
577 char *getStringCat2(char *s1, char *s2)
578 {
579   return getStringCat2WithSeparator(s1, s2, "");
580 }
581
582 char *getStringCat3(char *s1, char *s2, char *s3)
583 {
584   return getStringCat3WithSeparator(s1, s2, s3, "");
585 }
586
587 char *getPath2(char *path1, char *path2)
588 {
589 #if defined(PLATFORM_ANDROID)
590   // workaround for reading from APK assets directory -- skip leading "./"
591   if (strEqual(path1, "."))
592     return getStringCopy(path2);
593 #endif
594
595   return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
596 }
597
598 char *getPath3(char *path1, char *path2, char *path3)
599 {
600 #if defined(PLATFORM_ANDROID)
601   // workaround for reading from APK assets directory -- skip leading "./"
602   if (strEqual(path1, "."))
603     return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
604 #endif
605
606   return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
607 }
608
609 char *getStringCopy(const char *s)
610 {
611   char *s_copy;
612
613   if (s == NULL)
614     return NULL;
615
616   s_copy = checked_malloc(strlen(s) + 1);
617   strcpy(s_copy, s);
618
619   return s_copy;
620 }
621
622 char *getStringCopyN(const char *s, int n)
623 {
624   char *s_copy;
625   int s_len = MAX(0, n);
626
627   if (s == NULL)
628     return NULL;
629
630   s_copy = checked_malloc(s_len + 1);
631   strncpy(s_copy, s, s_len);
632   s_copy[s_len] = '\0';
633
634   return s_copy;
635 }
636
637 char *getStringCopyNStatic(const char *s, int n)
638 {
639   static char *s_copy = NULL;
640
641   checked_free(s_copy);
642
643   s_copy = getStringCopyN(s, n);
644
645   return s_copy;
646 }
647
648 char *getStringToLower(const char *s)
649 {
650   char *s_copy = checked_malloc(strlen(s) + 1);
651   char *s_ptr = s_copy;
652
653   while (*s)
654     *s_ptr++ = tolower(*s++);
655   *s_ptr = '\0';
656
657   return s_copy;
658 }
659
660 void setString(char **old_value, char *new_value)
661 {
662   checked_free(*old_value);
663
664   *old_value = getStringCopy(new_value);
665 }
666
667 boolean strEqual(char *s1, char *s2)
668 {
669   return (s1 == NULL && s2 == NULL ? TRUE  :
670           s1 == NULL && s2 != NULL ? FALSE :
671           s1 != NULL && s2 == NULL ? FALSE :
672           strcmp(s1, s2) == 0);
673 }
674
675 boolean strEqualN(char *s1, char *s2, int n)
676 {
677   return (s1 == NULL && s2 == NULL ? TRUE  :
678           s1 == NULL && s2 != NULL ? FALSE :
679           s1 != NULL && s2 == NULL ? FALSE :
680           strncmp(s1, s2, n) == 0);
681 }
682
683 boolean strPrefix(char *s, char *prefix)
684 {
685   return (s == NULL && prefix == NULL ? TRUE  :
686           s == NULL && prefix != NULL ? FALSE :
687           s != NULL && prefix == NULL ? FALSE :
688           strncmp(s, prefix, strlen(prefix)) == 0);
689 }
690
691 boolean strSuffix(char *s, char *suffix)
692 {
693   return (s == NULL && suffix == NULL ? TRUE  :
694           s == NULL && suffix != NULL ? FALSE :
695           s != NULL && suffix == NULL ? FALSE :
696           strlen(s) < strlen(suffix)  ? FALSE :
697           strncmp(&s[strlen(s) - strlen(suffix)], suffix, strlen(suffix)) == 0);
698 }
699
700 boolean strPrefixLower(char *s, char *prefix)
701 {
702   char *s_lower = getStringToLower(s);
703   boolean match = strPrefix(s_lower, prefix);
704
705   free(s_lower);
706
707   return match;
708 }
709
710 boolean strSuffixLower(char *s, char *suffix)
711 {
712   char *s_lower = getStringToLower(s);
713   boolean match = strSuffix(s_lower, suffix);
714
715   free(s_lower);
716
717   return match;
718 }
719
720
721 /* ------------------------------------------------------------------------- */
722 /* command line option handling functions                                    */
723 /* ------------------------------------------------------------------------- */
724
725 void GetOptions(char *argv[],
726                 void (*print_usage_function)(void),
727                 void (*print_version_function)(void))
728 {
729   char *ro_base_path = RO_BASE_PATH;
730   char *rw_base_path = RW_BASE_PATH;
731   char **options_left = &argv[1];
732
733   /* if the program is configured to start from current directory (default),
734      determine program package directory from program binary (some versions
735      of KDE/Konqueror and Mac OS X (especially "Mavericks") apparently do not
736      set the current working directory to the program package directory) */
737
738   if (strEqual(ro_base_path, "."))
739     ro_base_path = getProgramMainDataPath();
740   if (strEqual(rw_base_path, "."))
741     rw_base_path = getProgramMainDataPath();
742
743   /* initialize global program options */
744   options.display_name = NULL;
745   options.server_host = NULL;
746   options.server_port = 0;
747
748   options.ro_base_directory = ro_base_path;
749   options.rw_base_directory = rw_base_path;
750   options.level_directory    = getPath2(ro_base_path, LEVELS_DIRECTORY);
751   options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
752   options.sounds_directory   = getPath2(ro_base_path, SOUNDS_DIRECTORY);
753   options.music_directory    = getPath2(ro_base_path, MUSIC_DIRECTORY);
754   options.docs_directory     = getPath2(ro_base_path, DOCS_DIRECTORY);
755
756   options.execute_command = NULL;
757   options.special_flags = NULL;
758
759   options.serveronly = FALSE;
760   options.network = FALSE;
761   options.verbose = FALSE;
762   options.debug = FALSE;
763
764 #if 1
765   options.verbose = TRUE;
766 #else
767 #if !defined(PLATFORM_UNIX)
768   if (*options_left == NULL)    /* no options given -- enable verbose mode */
769     options.verbose = TRUE;
770 #endif
771 #endif
772
773   while (*options_left)
774   {
775     char option_str[MAX_OPTION_LEN];
776     char *option = options_left[0];
777     char *next_option = options_left[1];
778     char *option_arg = NULL;
779     int option_len = strlen(option);
780
781     if (option_len >= MAX_OPTION_LEN)
782       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
783
784     strcpy(option_str, option);                 /* copy argument into buffer */
785     option = option_str;
786
787     if (strEqual(option, "--"))                 /* stop scanning arguments */
788       break;
789
790     if (strPrefix(option, "--"))                /* treat '--' like '-' */
791       option++;
792
793     option_arg = strchr(option, '=');
794     if (option_arg == NULL)                     /* no '=' in option */
795       option_arg = next_option;
796     else
797     {
798       *option_arg++ = '\0';                     /* cut argument from option */
799       if (*option_arg == '\0')                  /* no argument after '=' */
800         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
801     }
802
803     option_len = strlen(option);
804
805     if (strEqual(option, "-"))
806     {
807       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
808     }
809     else if (strncmp(option, "-help", option_len) == 0)
810     {
811       print_usage_function();
812
813       exit(0);
814     }
815     else if (strncmp(option, "-display", option_len) == 0)
816     {
817       if (option_arg == NULL)
818         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
819
820       options.display_name = option_arg;
821       if (option_arg == next_option)
822         options_left++;
823     }
824     else if (strncmp(option, "-basepath", option_len) == 0)
825     {
826       if (option_arg == NULL)
827         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
828
829       /* this should be extended to separate options for ro and rw data */
830       options.ro_base_directory = ro_base_path = option_arg;
831       options.rw_base_directory = rw_base_path = option_arg;
832       if (option_arg == next_option)
833         options_left++;
834
835       /* adjust paths for sub-directories in base directory accordingly */
836       options.level_directory    = getPath2(ro_base_path, LEVELS_DIRECTORY);
837       options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
838       options.sounds_directory   = getPath2(ro_base_path, SOUNDS_DIRECTORY);
839       options.music_directory    = getPath2(ro_base_path, MUSIC_DIRECTORY);
840       options.docs_directory     = getPath2(ro_base_path, DOCS_DIRECTORY);
841     }
842     else if (strncmp(option, "-levels", option_len) == 0)
843     {
844       if (option_arg == NULL)
845         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
846
847       options.level_directory = option_arg;
848       if (option_arg == next_option)
849         options_left++;
850     }
851     else if (strncmp(option, "-graphics", option_len) == 0)
852     {
853       if (option_arg == NULL)
854         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
855
856       options.graphics_directory = option_arg;
857       if (option_arg == next_option)
858         options_left++;
859     }
860     else if (strncmp(option, "-sounds", option_len) == 0)
861     {
862       if (option_arg == NULL)
863         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
864
865       options.sounds_directory = option_arg;
866       if (option_arg == next_option)
867         options_left++;
868     }
869     else if (strncmp(option, "-music", option_len) == 0)
870     {
871       if (option_arg == NULL)
872         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
873
874       options.music_directory = option_arg;
875       if (option_arg == next_option)
876         options_left++;
877     }
878     else if (strncmp(option, "-network", option_len) == 0)
879     {
880       options.network = TRUE;
881     }
882     else if (strncmp(option, "-serveronly", option_len) == 0)
883     {
884       options.serveronly = TRUE;
885     }
886     else if (strncmp(option, "-debug", option_len) == 0)
887     {
888       options.debug = TRUE;
889     }
890     else if (strncmp(option, "-verbose", option_len) == 0)
891     {
892       options.verbose = TRUE;
893     }
894     else if (strncmp(option, "-version", option_len) == 0 ||
895              strncmp(option, "-V", option_len) == 0)
896     {
897       print_version_function();
898
899       exit(0);
900     }
901     else if (strPrefix(option, "-D"))
902     {
903       options.special_flags = getStringCopy(&option[2]);
904     }
905     else if (strncmp(option, "-execute", option_len) == 0)
906     {
907       if (option_arg == NULL)
908         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
909
910       options.execute_command = option_arg;
911       if (option_arg == next_option)
912         options_left++;
913
914       /* when doing batch processing, always enable verbose mode (warnings) */
915       options.verbose = TRUE;
916     }
917     else if (*option == '-')
918     {
919       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
920     }
921     else if (options.server_host == NULL)
922     {
923       options.server_host = *options_left;
924     }
925     else if (options.server_port == 0)
926     {
927       options.server_port = atoi(*options_left);
928       if (options.server_port < 1024)
929         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
930     }
931     else
932       Error(ERR_EXIT_HELP, "too many arguments");
933
934     options_left++;
935   }
936 }
937
938
939 /* ------------------------------------------------------------------------- */
940 /* error handling functions                                                  */
941 /* ------------------------------------------------------------------------- */
942
943 #define MAX_INTERNAL_ERROR_SIZE         1024
944
945 /* used by SetError() and GetError() to store internal error messages */
946 static char internal_error[MAX_INTERNAL_ERROR_SIZE];
947
948 void SetError(char *format, ...)
949 {
950   va_list ap;
951
952   va_start(ap, format);
953   vsnprintf(internal_error, MAX_INTERNAL_ERROR_SIZE, format, ap);
954   va_end(ap);
955 }
956
957 char *GetError()
958 {
959   return internal_error;
960 }
961
962 void Error(int mode, char *format, ...)
963 {
964   static boolean last_line_was_separator = FALSE;
965   char *process_name = "";
966
967 #if defined(PLATFORM_ANDROID)
968   android_log_prio = (mode & ERR_DEBUG ? ANDROID_LOG_DEBUG :
969                       mode & ERR_INFO ? ANDROID_LOG_INFO :
970                       mode & ERR_WARN ? ANDROID_LOG_WARN :
971                       mode & ERR_EXIT ? ANDROID_LOG_FATAL :
972                       ANDROID_LOG_UNKNOWN);
973 #endif
974
975   /* display warnings only when running in verbose mode */
976   if (mode & ERR_WARN && !options.verbose)
977     return;
978
979   if (mode == ERR_INFO_LINE)
980   {
981     if (!last_line_was_separator)
982       fprintf_line(program.error_file, format, 79);
983
984     last_line_was_separator = TRUE;
985
986     return;
987   }
988
989   last_line_was_separator = FALSE;
990
991   if (mode & ERR_SOUND_SERVER)
992     process_name = " sound server";
993   else if (mode & ERR_NETWORK_SERVER)
994     process_name = " network server";
995   else if (mode & ERR_NETWORK_CLIENT)
996     process_name = " network client **";
997
998   if (format)
999   {
1000     va_list ap;
1001
1002     fprintf_nonewline(program.error_file, "%s%s: ", program.command_basename,
1003                       process_name);
1004
1005     if (mode & ERR_WARN)
1006       fprintf_nonewline(program.error_file, "warning: ");
1007
1008     if (mode & ERR_EXIT)
1009       fprintf_nonewline(program.error_file, "fatal error: ");
1010
1011     va_start(ap, format);
1012     vfprintf_newline(program.error_file, format, ap);
1013     va_end(ap);
1014
1015     if ((mode & ERR_EXIT) && !(mode & ERR_FROM_SERVER))
1016     {
1017       va_start(ap, format);
1018       program.exit_message_function(format, ap);
1019       va_end(ap);
1020     }
1021   }
1022   
1023   if (mode & ERR_HELP)
1024     fprintf_newline(program.error_file,
1025                     "%s: Try option '--help' for more information.",
1026                     program.command_basename);
1027
1028   if (mode & ERR_EXIT)
1029     fprintf_newline(program.error_file, "%s%s: aborting",
1030                     program.command_basename, process_name);
1031
1032   if (mode & ERR_EXIT)
1033   {
1034     if (mode & ERR_FROM_SERVER)
1035       exit(1);                          /* child process: normal exit */
1036     else
1037       program.exit_function(1);         /* main process: clean up stuff */
1038   }
1039 }
1040
1041
1042 /* ------------------------------------------------------------------------- */
1043 /* checked memory allocation and freeing functions                           */
1044 /* ------------------------------------------------------------------------- */
1045
1046 void *checked_malloc(unsigned int size)
1047 {
1048   void *ptr;
1049
1050   ptr = malloc(size);
1051
1052   if (ptr == NULL)
1053     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1054
1055   return ptr;
1056 }
1057
1058 void *checked_calloc(unsigned int size)
1059 {
1060   void *ptr;
1061
1062   ptr = calloc(1, size);
1063
1064   if (ptr == NULL)
1065     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1066
1067   return ptr;
1068 }
1069
1070 void *checked_realloc(void *ptr, unsigned int size)
1071 {
1072   ptr = realloc(ptr, size);
1073
1074   if (ptr == NULL)
1075     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1076
1077   return ptr;
1078 }
1079
1080 void checked_free(void *ptr)
1081 {
1082   if (ptr != NULL)      /* this check should be done by free() anyway */
1083     free(ptr);
1084 }
1085
1086 void clear_mem(void *ptr, unsigned int size)
1087 {
1088 #if defined(PLATFORM_WIN32)
1089   /* for unknown reason, memset() sometimes crashes when compiled with MinGW */
1090   char *cptr = (char *)ptr;
1091
1092   while (size--)
1093     *cptr++ = 0;
1094 #else
1095   memset(ptr, 0, size);
1096 #endif
1097 }
1098
1099
1100 /* ------------------------------------------------------------------------- */
1101 /* various helper functions                                                  */
1102 /* ------------------------------------------------------------------------- */
1103
1104 inline void swap_numbers(int *i1, int *i2)
1105 {
1106   int help = *i1;
1107
1108   *i1 = *i2;
1109   *i2 = help;
1110 }
1111
1112 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1113 {
1114   int help_x = *x1;
1115   int help_y = *y1;
1116
1117   *x1 = *x2;
1118   *x2 = help_x;
1119
1120   *y1 = *y2;
1121   *y2 = help_y;
1122 }
1123
1124 /* the "put" variants of the following file access functions check for the file
1125    pointer being != NULL and return the number of bytes they have or would have
1126    written; this allows for chunk writing functions to first determine the size
1127    of the (not yet written) chunk, write the correct chunk size and finally
1128    write the chunk itself */
1129
1130 int getFile8BitInteger(File *file)
1131 {
1132   return getByteFromFile(file);
1133 }
1134
1135 int putFile8BitInteger(FILE *file, int value)
1136 {
1137   if (file != NULL)
1138     fputc(value, file);
1139
1140   return 1;
1141 }
1142
1143 int getFile16BitInteger(File *file, int byte_order)
1144 {
1145   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1146     return ((getByteFromFile(file) << 8) |
1147             (getByteFromFile(file) << 0));
1148   else           /* BYTE_ORDER_LITTLE_ENDIAN */
1149     return ((getByteFromFile(file) << 0) |
1150             (getByteFromFile(file) << 8));
1151 }
1152
1153 int putFile16BitInteger(FILE *file, int value, int byte_order)
1154 {
1155   if (file != NULL)
1156   {
1157     if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1158     {
1159       fputc((value >> 8) & 0xff, file);
1160       fputc((value >> 0) & 0xff, file);
1161     }
1162     else           /* BYTE_ORDER_LITTLE_ENDIAN */
1163     {
1164       fputc((value >> 0) & 0xff, file);
1165       fputc((value >> 8) & 0xff, file);
1166     }
1167   }
1168
1169   return 2;
1170 }
1171
1172 int getFile32BitInteger(File *file, int byte_order)
1173 {
1174   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1175     return ((getByteFromFile(file) << 24) |
1176             (getByteFromFile(file) << 16) |
1177             (getByteFromFile(file) <<  8) |
1178             (getByteFromFile(file) <<  0));
1179   else           /* BYTE_ORDER_LITTLE_ENDIAN */
1180     return ((getByteFromFile(file) <<  0) |
1181             (getByteFromFile(file) <<  8) |
1182             (getByteFromFile(file) << 16) |
1183             (getByteFromFile(file) << 24));
1184 }
1185
1186 int putFile32BitInteger(FILE *file, int value, int byte_order)
1187 {
1188   if (file != NULL)
1189   {
1190     if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1191     {
1192       fputc((value >> 24) & 0xff, file);
1193       fputc((value >> 16) & 0xff, file);
1194       fputc((value >>  8) & 0xff, file);
1195       fputc((value >>  0) & 0xff, file);
1196     }
1197     else           /* BYTE_ORDER_LITTLE_ENDIAN */
1198     {
1199       fputc((value >>  0) & 0xff, file);
1200       fputc((value >>  8) & 0xff, file);
1201       fputc((value >> 16) & 0xff, file);
1202       fputc((value >> 24) & 0xff, file);
1203     }
1204   }
1205
1206   return 4;
1207 }
1208
1209 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1210                      int byte_order)
1211 {
1212   const int chunk_name_length = 4;
1213
1214   /* read chunk name */
1215   if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1216     return FALSE;
1217
1218   if (chunk_size != NULL)
1219   {
1220     /* read chunk size */
1221     *chunk_size = getFile32BitInteger(file, byte_order);
1222   }
1223
1224   return (checkEndOfFile(file) ? FALSE : TRUE);
1225 }
1226
1227 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1228                  int byte_order)
1229 {
1230   int num_bytes = 0;
1231
1232   /* write chunk name */
1233   if (file != NULL)
1234     fputs(chunk_name, file);
1235
1236   num_bytes += strlen(chunk_name);
1237
1238   if (chunk_size >= 0)
1239   {
1240     /* write chunk size */
1241     if (file != NULL)
1242       putFile32BitInteger(file, chunk_size, byte_order);
1243
1244     num_bytes += 4;
1245   }
1246
1247   return num_bytes;
1248 }
1249
1250 int getFileVersion(File *file)
1251 {
1252   int version_major = getByteFromFile(file);
1253   int version_minor = getByteFromFile(file);
1254   int version_patch = getByteFromFile(file);
1255   int version_build = getByteFromFile(file);
1256
1257   return VERSION_IDENT(version_major, version_minor, version_patch,
1258                        version_build);
1259 }
1260
1261 int putFileVersion(FILE *file, int version)
1262 {
1263   if (file != NULL)
1264   {
1265     int version_major = VERSION_MAJOR(version);
1266     int version_minor = VERSION_MINOR(version);
1267     int version_patch = VERSION_PATCH(version);
1268     int version_build = VERSION_BUILD(version);
1269
1270     fputc(version_major, file);
1271     fputc(version_minor, file);
1272     fputc(version_patch, file);
1273     fputc(version_build, file);
1274   }
1275
1276   return 4;
1277 }
1278
1279 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1280 {
1281   int i;
1282
1283   for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1284     buffer[i] = getByteFromFile(file);
1285 }
1286
1287 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1288 {
1289   int i;
1290
1291   for(i = 0; i < bytes; i++)
1292     fputc(buffer[i], file);
1293 }
1294
1295 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1296 {
1297   while (bytes-- && !checkEndOfFile(file))
1298     getByteFromFile(file);
1299 }
1300
1301 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1302 {
1303   while (bytes--)
1304     fputc(0, file);
1305 }
1306
1307
1308 /* ------------------------------------------------------------------------- */
1309 /* functions to translate key identifiers between different format           */
1310 /* ------------------------------------------------------------------------- */
1311
1312 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
1313 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
1314 #define TRANSLATE_KEYNAME_TO_KEYSYM     2
1315 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  3
1316
1317 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1318 {
1319   static struct
1320   {
1321     Key key;
1322     char *x11name;
1323     char *name;
1324   } translate_key[] =
1325   {
1326     /* normal cursor keys */
1327     { KSYM_Left,        "XK_Left",              "cursor left" },
1328     { KSYM_Right,       "XK_Right",             "cursor right" },
1329     { KSYM_Up,          "XK_Up",                "cursor up" },
1330     { KSYM_Down,        "XK_Down",              "cursor down" },
1331
1332     /* keypad cursor keys */
1333 #ifdef KSYM_KP_Left
1334     { KSYM_KP_Left,     "XK_KP_Left",           "keypad left" },
1335     { KSYM_KP_Right,    "XK_KP_Right",          "keypad right" },
1336     { KSYM_KP_Up,       "XK_KP_Up",             "keypad up" },
1337     { KSYM_KP_Down,     "XK_KP_Down",           "keypad down" },
1338 #endif
1339
1340     /* other keypad keys */
1341 #ifdef KSYM_KP_Enter
1342     { KSYM_KP_Enter,    "XK_KP_Enter",          "keypad enter" },
1343     { KSYM_KP_Add,      "XK_KP_Add",            "keypad +" },
1344     { KSYM_KP_Subtract, "XK_KP_Subtract",       "keypad -" },
1345     { KSYM_KP_Multiply, "XK_KP_Multiply",       "keypad mltply" },
1346     { KSYM_KP_Divide,   "XK_KP_Divide",         "keypad /" },
1347     { KSYM_KP_Separator,"XK_KP_Separator",      "keypad ," },
1348 #endif
1349
1350     /* modifier keys */
1351     { KSYM_Shift_L,     "XK_Shift_L",           "left shift" },
1352     { KSYM_Shift_R,     "XK_Shift_R",           "right shift" },
1353     { KSYM_Control_L,   "XK_Control_L",         "left control" },
1354     { KSYM_Control_R,   "XK_Control_R",         "right control" },
1355     { KSYM_Meta_L,      "XK_Meta_L",            "left meta" },
1356     { KSYM_Meta_R,      "XK_Meta_R",            "right meta" },
1357     { KSYM_Alt_L,       "XK_Alt_L",             "left alt" },
1358     { KSYM_Alt_R,       "XK_Alt_R",             "right alt" },
1359 #if !defined(TARGET_SDL2)
1360     { KSYM_Super_L,     "XK_Super_L",           "left super" },  /* Win-L */
1361     { KSYM_Super_R,     "XK_Super_R",           "right super" }, /* Win-R */
1362 #endif
1363     { KSYM_Mode_switch, "XK_Mode_switch",       "mode switch" }, /* Alt-R */
1364     { KSYM_Multi_key,   "XK_Multi_key",         "multi key" },   /* Ctrl-R */
1365
1366     /* some special keys */
1367     { KSYM_BackSpace,   "XK_BackSpace",         "backspace" },
1368     { KSYM_Delete,      "XK_Delete",            "delete" },
1369     { KSYM_Insert,      "XK_Insert",            "insert" },
1370     { KSYM_Tab,         "XK_Tab",               "tab" },
1371     { KSYM_Home,        "XK_Home",              "home" },
1372     { KSYM_End,         "XK_End",               "end" },
1373     { KSYM_Page_Up,     "XK_Page_Up",           "page up" },
1374     { KSYM_Page_Down,   "XK_Page_Down",         "page down" },
1375
1376 #if defined(TARGET_SDL2)
1377     { KSYM_Menu,        "XK_Menu",              "menu" },        /* menu key */
1378     { KSYM_Back,        "XK_Back",              "back" },        /* back key */
1379 #endif
1380
1381     /* ASCII 0x20 to 0x40 keys (except numbers) */
1382     { KSYM_space,       "XK_space",             "space" },
1383     { KSYM_exclam,      "XK_exclam",            "!" },
1384     { KSYM_quotedbl,    "XK_quotedbl",          "\"" },
1385     { KSYM_numbersign,  "XK_numbersign",        "#" },
1386     { KSYM_dollar,      "XK_dollar",            "$" },
1387     { KSYM_percent,     "XK_percent",           "%" },
1388     { KSYM_ampersand,   "XK_ampersand",         "&" },
1389     { KSYM_apostrophe,  "XK_apostrophe",        "'" },
1390     { KSYM_parenleft,   "XK_parenleft",         "(" },
1391     { KSYM_parenright,  "XK_parenright",        ")" },
1392     { KSYM_asterisk,    "XK_asterisk",          "*" },
1393     { KSYM_plus,        "XK_plus",              "+" },
1394     { KSYM_comma,       "XK_comma",             "," },
1395     { KSYM_minus,       "XK_minus",             "-" },
1396     { KSYM_period,      "XK_period",            "." },
1397     { KSYM_slash,       "XK_slash",             "/" },
1398     { KSYM_colon,       "XK_colon",             ":" },
1399     { KSYM_semicolon,   "XK_semicolon",         ";" },
1400     { KSYM_less,        "XK_less",              "<" },
1401     { KSYM_equal,       "XK_equal",             "=" },
1402     { KSYM_greater,     "XK_greater",           ">" },
1403     { KSYM_question,    "XK_question",          "?" },
1404     { KSYM_at,          "XK_at",                "@" },
1405
1406     /* more ASCII keys */
1407     { KSYM_bracketleft, "XK_bracketleft",       "[" },
1408     { KSYM_backslash,   "XK_backslash",         "\\" },
1409     { KSYM_bracketright,"XK_bracketright",      "]" },
1410     { KSYM_asciicircum, "XK_asciicircum",       "^" },
1411     { KSYM_underscore,  "XK_underscore",        "_" },
1412     { KSYM_grave,       "XK_grave",             "grave" },
1413     { KSYM_quoteleft,   "XK_quoteleft",         "quote left" },
1414     { KSYM_braceleft,   "XK_braceleft",         "brace left" },
1415     { KSYM_bar,         "XK_bar",               "bar" },
1416     { KSYM_braceright,  "XK_braceright",        "brace right" },
1417     { KSYM_asciitilde,  "XK_asciitilde",        "~" },
1418
1419     /* special (non-ASCII) keys */
1420     { KSYM_degree,      "XK_degree",            "degree" },
1421     { KSYM_Adiaeresis,  "XK_Adiaeresis",        "A umlaut" },
1422     { KSYM_Odiaeresis,  "XK_Odiaeresis",        "O umlaut" },
1423     { KSYM_Udiaeresis,  "XK_Udiaeresis",        "U umlaut" },
1424     { KSYM_adiaeresis,  "XK_adiaeresis",        "a umlaut" },
1425     { KSYM_odiaeresis,  "XK_odiaeresis",        "o umlaut" },
1426     { KSYM_udiaeresis,  "XK_udiaeresis",        "u umlaut" },
1427     { KSYM_ssharp,      "XK_ssharp",            "sharp s" },
1428
1429 #if defined(TARGET_SDL2)
1430     /* special (non-ASCII) keys (UTF-8, for reverse mapping only) */
1431     { KSYM_degree,      "XK_degree",            "\xc2\xb0" },
1432     { KSYM_Adiaeresis,  "XK_Adiaeresis",        "\xc3\x84" },
1433     { KSYM_Odiaeresis,  "XK_Odiaeresis",        "\xc3\x96" },
1434     { KSYM_Udiaeresis,  "XK_Udiaeresis",        "\xc3\x9c" },
1435     { KSYM_adiaeresis,  "XK_adiaeresis",        "\xc3\xa4" },
1436     { KSYM_odiaeresis,  "XK_odiaeresis",        "\xc3\xb6" },
1437     { KSYM_udiaeresis,  "XK_udiaeresis",        "\xc3\xbc" },
1438     { KSYM_ssharp,      "XK_ssharp",            "\xc3\x9f" },
1439
1440     /* other keys (for reverse mapping only) */
1441     { KSYM_space,       "XK_space",             " " },
1442 #endif
1443
1444 #if defined(TARGET_SDL2)
1445     /* keypad keys are not in numerical order in SDL2 */
1446     { KSYM_KP_0,        "XK_KP_0",              "keypad 0" },
1447     { KSYM_KP_1,        "XK_KP_1",              "keypad 1" },
1448     { KSYM_KP_2,        "XK_KP_2",              "keypad 2" },
1449     { KSYM_KP_3,        "XK_KP_3",              "keypad 3" },
1450     { KSYM_KP_4,        "XK_KP_4",              "keypad 4" },
1451     { KSYM_KP_5,        "XK_KP_5",              "keypad 5" },
1452     { KSYM_KP_6,        "XK_KP_6",              "keypad 6" },
1453     { KSYM_KP_7,        "XK_KP_7",              "keypad 7" },
1454     { KSYM_KP_8,        "XK_KP_8",              "keypad 8" },
1455     { KSYM_KP_9,        "XK_KP_9",              "keypad 9" },
1456 #endif
1457
1458     /* end-of-array identifier */
1459     { 0,                NULL,                   NULL }
1460   };
1461
1462   int i;
1463
1464   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1465   {
1466     static char name_buffer[30];
1467     Key key = *keysym;
1468
1469     if (key >= KSYM_A && key <= KSYM_Z)
1470       sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1471     else if (key >= KSYM_a && key <= KSYM_z)
1472       sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1473     else if (key >= KSYM_0 && key <= KSYM_9)
1474       sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1475 #if !defined(TARGET_SDL2)
1476     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1477       sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1478 #endif
1479     else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1480       sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1481     else if (key == KSYM_UNDEFINED)
1482       strcpy(name_buffer, "(undefined)");
1483     else
1484     {
1485       i = 0;
1486
1487       do
1488       {
1489         if (key == translate_key[i].key)
1490         {
1491           strcpy(name_buffer, translate_key[i].name);
1492           break;
1493         }
1494       }
1495       while (translate_key[++i].name);
1496
1497       if (!translate_key[i].name)
1498         strcpy(name_buffer, "(unknown)");
1499     }
1500
1501     *name = name_buffer;
1502   }
1503   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1504   {
1505     static char name_buffer[30];
1506     Key key = *keysym;
1507
1508     if (key >= KSYM_A && key <= KSYM_Z)
1509       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1510     else if (key >= KSYM_a && key <= KSYM_z)
1511       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1512     else if (key >= KSYM_0 && key <= KSYM_9)
1513       sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1514 #if !defined(TARGET_SDL2)
1515     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1516       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1517 #endif
1518     else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1519       sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1520     else if (key == KSYM_UNDEFINED)
1521       strcpy(name_buffer, "[undefined]");
1522     else
1523     {
1524       i = 0;
1525
1526       do
1527       {
1528         if (key == translate_key[i].key)
1529         {
1530           strcpy(name_buffer, translate_key[i].x11name);
1531           break;
1532         }
1533       }
1534       while (translate_key[++i].x11name);
1535
1536       if (!translate_key[i].x11name)
1537         sprintf(name_buffer, "0x%04x", (unsigned int)key);
1538     }
1539
1540     *x11name = name_buffer;
1541   }
1542   else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1543   {
1544     Key key = KSYM_UNDEFINED;
1545     char *name_ptr = *name;
1546
1547     if (strlen(*name) == 1)
1548     {
1549       char c = name_ptr[0];
1550
1551       if (c >= 'A' && c <= 'Z')
1552         key = KSYM_A + (Key)(c - 'A');
1553       else if (c >= 'a' && c <= 'z')
1554         key = KSYM_a + (Key)(c - 'a');
1555       else if (c >= '0' && c <= '9')
1556         key = KSYM_0 + (Key)(c - '0');
1557     }
1558
1559     if (key == KSYM_UNDEFINED)
1560     {
1561       i = 0;
1562
1563       do
1564       {
1565         if (strEqual(translate_key[i].name, *name))
1566         {
1567           key = translate_key[i].key;
1568           break;
1569         }
1570       }
1571       while (translate_key[++i].x11name);
1572     }
1573
1574     if (key == KSYM_UNDEFINED)
1575       Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1576
1577     *keysym = key;
1578   }
1579   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1580   {
1581     Key key = KSYM_UNDEFINED;
1582     char *name_ptr = *x11name;
1583
1584     if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
1585     {
1586       char c = name_ptr[3];
1587
1588       if (c >= 'A' && c <= 'Z')
1589         key = KSYM_A + (Key)(c - 'A');
1590       else if (c >= 'a' && c <= 'z')
1591         key = KSYM_a + (Key)(c - 'a');
1592       else if (c >= '0' && c <= '9')
1593         key = KSYM_0 + (Key)(c - '0');
1594     }
1595 #if !defined(TARGET_SDL2)
1596     else if (strPrefix(name_ptr, "XK_KP_") && strlen(name_ptr) == 7)
1597     {
1598       char c = name_ptr[6];
1599
1600       if (c >= '0' && c <= '9')
1601         key = KSYM_KP_0 + (Key)(c - '0');
1602     }
1603 #endif
1604     else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
1605     {
1606       char c1 = name_ptr[4];
1607       char c2 = name_ptr[5];
1608       int d = 0;
1609
1610       if ((c1 >= '0' && c1 <= '9') &&
1611           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1612         d = atoi(&name_ptr[4]);
1613
1614       if (d >= 1 && d <= KSYM_NUM_FKEYS)
1615         key = KSYM_F1 + (Key)(d - 1);
1616     }
1617     else if (strPrefix(name_ptr, "XK_"))
1618     {
1619       i = 0;
1620
1621       do
1622       {
1623         if (strEqual(name_ptr, translate_key[i].x11name))
1624         {
1625           key = translate_key[i].key;
1626           break;
1627         }
1628       }
1629       while (translate_key[++i].x11name);
1630     }
1631     else if (strPrefix(name_ptr, "0x"))
1632     {
1633       unsigned int value = 0;
1634
1635       name_ptr += 2;
1636
1637       while (name_ptr)
1638       {
1639         char c = *name_ptr++;
1640         int d = -1;
1641
1642         if (c >= '0' && c <= '9')
1643           d = (int)(c - '0');
1644         else if (c >= 'a' && c <= 'f')
1645           d = (int)(c - 'a' + 10);
1646         else if (c >= 'A' && c <= 'F')
1647           d = (int)(c - 'A' + 10);
1648
1649         if (d == -1)
1650         {
1651           value = -1;
1652           break;
1653         }
1654
1655         value = value * 16 + d;
1656       }
1657
1658       if (value != -1)
1659         key = (Key)value;
1660     }
1661
1662     *keysym = key;
1663   }
1664 }
1665
1666 char *getKeyNameFromKey(Key key)
1667 {
1668   char *name;
1669
1670   translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1671   return name;
1672 }
1673
1674 char *getX11KeyNameFromKey(Key key)
1675 {
1676   char *x11name;
1677
1678   translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1679   return x11name;
1680 }
1681
1682 Key getKeyFromKeyName(char *name)
1683 {
1684   Key key;
1685
1686   translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1687   return key;
1688 }
1689
1690 Key getKeyFromX11KeyName(char *x11name)
1691 {
1692   Key key;
1693
1694   translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1695   return key;
1696 }
1697
1698 char getCharFromKey(Key key)
1699 {
1700   static struct
1701   {
1702     Key key;
1703     byte key_char;
1704   } translate_key_char[] =
1705   {
1706     /* special (non-ASCII) keys (ISO-8859-1) */
1707     { KSYM_degree,      CHAR_BYTE_DEGREE        },
1708     { KSYM_Adiaeresis,  CHAR_BYTE_UMLAUT_A      },
1709     { KSYM_Odiaeresis,  CHAR_BYTE_UMLAUT_O      },
1710     { KSYM_Udiaeresis,  CHAR_BYTE_UMLAUT_U      },
1711     { KSYM_adiaeresis,  CHAR_BYTE_UMLAUT_a      },
1712     { KSYM_odiaeresis,  CHAR_BYTE_UMLAUT_o      },
1713     { KSYM_udiaeresis,  CHAR_BYTE_UMLAUT_u      },
1714     { KSYM_ssharp,      CHAR_BYTE_SHARP_S       },
1715
1716     /* end-of-array identifier */
1717     { 0,                0                       }
1718   };
1719
1720   char *keyname = getKeyNameFromKey(key);
1721   char c = 0;
1722
1723   if (strlen(keyname) == 1)
1724     c = keyname[0];
1725   else if (strEqual(keyname, "space"))
1726     c = ' ';
1727   else
1728   {
1729     int i = 0;
1730
1731     do
1732     {
1733       if (key == translate_key_char[i].key)
1734       {
1735         c = translate_key_char[i].key_char;
1736
1737         break;
1738       }
1739     }
1740     while (translate_key_char[++i].key_char);
1741   }
1742
1743   return c;
1744 }
1745
1746 char getValidConfigValueChar(char c)
1747 {
1748   if (c == '#' ||       /* used to mark comments */
1749       c == '\\')        /* used to mark continued lines */
1750     c = 0;
1751
1752   return c;
1753 }
1754
1755
1756 /* ------------------------------------------------------------------------- */
1757 /* functions to translate string identifiers to integer or boolean value     */
1758 /* ------------------------------------------------------------------------- */
1759
1760 int get_integer_from_string(char *s)
1761 {
1762   static char *number_text[][3] =
1763   {
1764     { "0",      "zero",         "null",         },
1765     { "1",      "one",          "first"         },
1766     { "2",      "two",          "second"        },
1767     { "3",      "three",        "third"         },
1768     { "4",      "four",         "fourth"        },
1769     { "5",      "five",         "fifth"         },
1770     { "6",      "six",          "sixth"         },
1771     { "7",      "seven",        "seventh"       },
1772     { "8",      "eight",        "eighth"        },
1773     { "9",      "nine",         "ninth"         },
1774     { "10",     "ten",          "tenth"         },
1775     { "11",     "eleven",       "eleventh"      },
1776     { "12",     "twelve",       "twelfth"       },
1777
1778     { NULL,     NULL,           NULL            },
1779   };
1780
1781   int i, j;
1782   char *s_lower = getStringToLower(s);
1783   int result = -1;
1784
1785   for (i = 0; number_text[i][0] != NULL; i++)
1786     for (j = 0; j < 3; j++)
1787       if (strEqual(s_lower, number_text[i][j]))
1788         result = i;
1789
1790   if (result == -1)
1791   {
1792     if (strEqual(s_lower, "false") ||
1793         strEqual(s_lower, "no") ||
1794         strEqual(s_lower, "off"))
1795       result = 0;
1796     else if (strEqual(s_lower, "true") ||
1797              strEqual(s_lower, "yes") ||
1798              strEqual(s_lower, "on"))
1799       result = 1;
1800     else
1801       result = atoi(s);
1802   }
1803
1804   free(s_lower);
1805
1806   return result;
1807 }
1808
1809 boolean get_boolean_from_string(char *s)
1810 {
1811   char *s_lower = getStringToLower(s);
1812   boolean result = FALSE;
1813
1814   if (strEqual(s_lower, "true") ||
1815       strEqual(s_lower, "yes") ||
1816       strEqual(s_lower, "on") ||
1817       get_integer_from_string(s) == 1)
1818     result = TRUE;
1819
1820   free(s_lower);
1821
1822   return result;
1823 }
1824
1825 int get_switch3_from_string(char *s)
1826 {
1827   char *s_lower = getStringToLower(s);
1828   int result = FALSE;
1829
1830   if (strEqual(s_lower, "true") ||
1831       strEqual(s_lower, "yes") ||
1832       strEqual(s_lower, "on") ||
1833       get_integer_from_string(s) == 1)
1834     result = TRUE;
1835   else if (strEqual(s_lower, "auto"))
1836     result = AUTO;
1837
1838   free(s_lower);
1839
1840   return result;
1841 }
1842
1843
1844 /* ------------------------------------------------------------------------- */
1845 /* functions for generic lists                                               */
1846 /* ------------------------------------------------------------------------- */
1847
1848 ListNode *newListNode()
1849 {
1850   return checked_calloc(sizeof(ListNode));
1851 }
1852
1853 void addNodeToList(ListNode **node_first, char *key, void *content)
1854 {
1855   ListNode *node_new = newListNode();
1856
1857   node_new->key = getStringCopy(key);
1858   node_new->content = content;
1859   node_new->next = *node_first;
1860   *node_first = node_new;
1861 }
1862
1863 void deleteNodeFromList(ListNode **node_first, char *key,
1864                         void (*destructor_function)(void *))
1865 {
1866   if (node_first == NULL || *node_first == NULL)
1867     return;
1868
1869   if (strEqual((*node_first)->key, key))
1870   {
1871     checked_free((*node_first)->key);
1872     if (destructor_function)
1873       destructor_function((*node_first)->content);
1874     *node_first = (*node_first)->next;
1875   }
1876   else
1877     deleteNodeFromList(&(*node_first)->next, key, destructor_function);
1878 }
1879
1880 ListNode *getNodeFromKey(ListNode *node_first, char *key)
1881 {
1882   if (node_first == NULL)
1883     return NULL;
1884
1885   if (strEqual(node_first->key, key))
1886     return node_first;
1887   else
1888     return getNodeFromKey(node_first->next, key);
1889 }
1890
1891 int getNumNodes(ListNode *node_first)
1892 {
1893   return (node_first ? 1 + getNumNodes(node_first->next) : 0);
1894 }
1895
1896 void dumpList(ListNode *node_first)
1897 {
1898   ListNode *node = node_first;
1899
1900   while (node)
1901   {
1902     printf("['%s' (%d)]\n", node->key,
1903            ((struct ListNodeInfo *)node->content)->num_references);
1904     node = node->next;
1905   }
1906
1907   printf("[%d nodes]\n", getNumNodes(node_first));
1908 }
1909
1910
1911 /* ------------------------------------------------------------------------- */
1912 /* functions for file handling                                               */
1913 /* ------------------------------------------------------------------------- */
1914
1915 File *openFile(char *filename, char *mode)
1916 {
1917   File *file = checked_calloc(sizeof(File));
1918
1919   file->file = fopen(filename, mode);
1920
1921   if (file->file != NULL)
1922   {
1923     file->filename = getStringCopy(filename);
1924
1925     return file;
1926   }
1927
1928 #if defined(PLATFORM_ANDROID)
1929   file->asset_file = SDL_RWFromFile(filename, mode);
1930
1931   if (file->asset_file != NULL)
1932   {
1933     file->file_is_asset = TRUE;
1934     file->filename = getStringCopy(filename);
1935
1936     return file;
1937   }
1938 #endif
1939
1940   checked_free(file);
1941
1942   return NULL;
1943 }
1944
1945 int closeFile(File *file)
1946 {
1947   if (file == NULL)
1948     return -1;
1949
1950   int result = 0;
1951
1952 #if defined(PLATFORM_ANDROID)
1953   if (file->asset_file)
1954     result = SDL_RWclose(file->asset_file);
1955 #endif
1956
1957   if (file->file)
1958     result = fclose(file->file);
1959
1960   checked_free(file->filename);
1961   checked_free(file);
1962
1963   return result;
1964 }
1965
1966 int checkEndOfFile(File *file)
1967 {
1968 #if defined(PLATFORM_ANDROID)
1969   if (file->file_is_asset)
1970     return file->end_of_file;
1971 #endif
1972
1973   return feof(file->file);
1974 }
1975
1976 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
1977 {
1978 #if defined(PLATFORM_ANDROID)
1979   if (file->file_is_asset)
1980   {
1981     if (file->end_of_file)
1982       return 0;
1983
1984     size_t num_items_read =
1985       SDL_RWread(file->asset_file, buffer, item_size, num_items);
1986
1987     if (num_items_read < num_items)
1988       file->end_of_file = TRUE;
1989
1990     return num_items_read;
1991   }
1992 #endif
1993
1994   return fread(buffer, item_size, num_items, file->file);
1995 }
1996
1997 int seekFile(File *file, long offset, int whence)
1998 {
1999 #if defined(PLATFORM_ANDROID)
2000   if (file->file_is_asset)
2001   {
2002     int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2003                       whence == SEEK_CUR ? RW_SEEK_CUR :
2004                       whence == SEEK_END ? RW_SEEK_END : 0);
2005
2006     return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2007   }
2008 #endif
2009
2010   return fseek(file->file, offset, whence);
2011 }
2012
2013 int getByteFromFile(File *file)
2014 {
2015 #if defined(PLATFORM_ANDROID)
2016   if (file->file_is_asset)
2017   {
2018     if (file->end_of_file)
2019       return EOF;
2020
2021     byte c;
2022     size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2023
2024     if (num_bytes_read < 1)
2025       file->end_of_file = TRUE;
2026
2027     return (file->end_of_file ? EOF : (int)c);
2028   }
2029 #endif
2030
2031   return fgetc(file->file);
2032 }
2033
2034 char *getStringFromFile(File *file, char *line, int size)
2035 {
2036 #if defined(PLATFORM_ANDROID)
2037   if (file->file_is_asset)
2038   {
2039     if (file->end_of_file)
2040       return NULL;
2041
2042     char *line_ptr = line;
2043     int num_bytes_read = 0;
2044
2045     while (num_bytes_read < size - 1 &&
2046            SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2047            *line_ptr++ != '\n')
2048       num_bytes_read++;
2049
2050     *line_ptr = '\0';
2051
2052     if (strlen(line) == 0)
2053     {
2054       file->end_of_file = TRUE;
2055
2056       return NULL;
2057     }
2058
2059     return line;
2060   }
2061 #endif
2062
2063   return fgets(line, size, file->file);
2064 }
2065
2066
2067 /* ------------------------------------------------------------------------- */
2068 /* functions for directory handling                                          */
2069 /* ------------------------------------------------------------------------- */
2070
2071 Directory *openDirectory(char *dir_name)
2072 {
2073   Directory *dir = checked_calloc(sizeof(Directory));
2074
2075   dir->dir = opendir(dir_name);
2076
2077   if (dir->dir != NULL)
2078   {
2079     dir->filename = getStringCopy(dir_name);
2080
2081     return dir;
2082   }
2083
2084 #if defined(PLATFORM_ANDROID)
2085   char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2086
2087   dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2088
2089   checked_free(asset_toc_filename);
2090
2091   if (dir->asset_toc_file != NULL)
2092   {
2093     dir->directory_is_asset = TRUE;
2094     dir->filename = getStringCopy(dir_name);
2095
2096     return dir;
2097   }
2098 #endif
2099
2100   checked_free(dir);
2101
2102   return NULL;
2103 }
2104
2105 int closeDirectory(Directory *dir)
2106 {
2107   if (dir == NULL)
2108     return -1;
2109
2110   int result = 0;
2111
2112 #if defined(PLATFORM_ANDROID)
2113   if (dir->asset_toc_file)
2114     result = SDL_RWclose(dir->asset_toc_file);
2115 #endif
2116
2117   if (dir->dir)
2118     result = closedir(dir->dir);
2119
2120   if (dir->dir_entry)
2121     freeDirectoryEntry(dir->dir_entry);
2122
2123   checked_free(dir->filename);
2124   checked_free(dir);
2125
2126   return result;
2127 }
2128
2129 DirectoryEntry *readDirectory(Directory *dir)
2130 {
2131   if (dir->dir_entry)
2132     freeDirectoryEntry(dir->dir_entry);
2133
2134   dir->dir_entry = NULL;
2135
2136 #if defined(PLATFORM_ANDROID)
2137   if (dir->directory_is_asset)
2138   {
2139     char line[MAX_LINE_LEN];
2140     char *line_ptr = line;
2141     int num_bytes_read = 0;
2142
2143     while (num_bytes_read < MAX_LINE_LEN - 1 &&
2144            SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2145            *line_ptr != '\n')
2146     {
2147       line_ptr++;
2148       num_bytes_read++;
2149     }
2150
2151     *line_ptr = '\0';
2152
2153     if (strlen(line) == 0)
2154       return NULL;
2155
2156     dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2157
2158     dir->dir_entry->is_directory = FALSE;
2159     if (line[strlen(line) - 1] == '/')
2160     {
2161       dir->dir_entry->is_directory = TRUE;
2162
2163       line[strlen(line) - 1] = '\0';
2164     }
2165
2166     dir->dir_entry->basename = getStringCopy(line);
2167     dir->dir_entry->filename = getPath2(dir->filename, line);
2168
2169     return dir->dir_entry;
2170   }
2171 #endif
2172
2173   struct dirent *dir_entry = readdir(dir->dir);
2174
2175   if (dir_entry == NULL)
2176     return NULL;
2177
2178   dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2179
2180   dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2181   dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2182
2183   struct stat file_status;
2184
2185   dir->dir_entry->is_directory =
2186     (stat(dir->dir_entry->filename, &file_status) == 0 &&
2187      (file_status.st_mode & S_IFMT) == S_IFDIR);
2188
2189   return dir->dir_entry;
2190 }
2191
2192 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2193 {
2194   if (dir_entry == NULL)
2195     return;
2196
2197   checked_free(dir_entry->basename);
2198   checked_free(dir_entry->filename);
2199   checked_free(dir_entry);
2200 }
2201
2202
2203 /* ------------------------------------------------------------------------- */
2204 /* functions for checking files and filenames                                */
2205 /* ------------------------------------------------------------------------- */
2206
2207 boolean directoryExists(char *dir_name)
2208 {
2209   if (dir_name == NULL)
2210     return FALSE;
2211
2212   struct stat file_status;
2213   boolean success = (stat(dir_name, &file_status) == 0 &&
2214                      (file_status.st_mode & S_IFMT) == S_IFDIR);
2215
2216 #if defined(PLATFORM_ANDROID)
2217   if (!success)
2218   {
2219     // this might be an asset directory; check by trying to open toc file
2220     char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2221     SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2222
2223     checked_free(asset_toc_filename);
2224
2225     success = (file != NULL);
2226
2227     if (success)
2228       SDL_RWclose(file);
2229   }
2230 #endif
2231
2232   return success;
2233 }
2234
2235 boolean fileExists(char *filename)
2236 {
2237   if (filename == NULL)
2238     return FALSE;
2239
2240   boolean success = (access(filename, F_OK) == 0);
2241
2242 #if defined(PLATFORM_ANDROID)
2243   if (!success)
2244   {
2245     // this might be an asset file; check by trying to open it
2246     SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
2247
2248     success = (file != NULL);
2249
2250     if (success)
2251       SDL_RWclose(file);
2252   }
2253 #endif
2254
2255   return success;
2256 }
2257
2258 boolean fileHasPrefix(char *basename, char *prefix)
2259 {
2260   static char *basename_lower = NULL;
2261   int basename_length, prefix_length;
2262
2263   checked_free(basename_lower);
2264
2265   if (basename == NULL || prefix == NULL)
2266     return FALSE;
2267
2268   basename_lower = getStringToLower(basename);
2269   basename_length = strlen(basename_lower);
2270   prefix_length = strlen(prefix);
2271
2272   if (basename_length > prefix_length + 1 &&
2273       basename_lower[prefix_length] == '.' &&
2274       strncmp(basename_lower, prefix, prefix_length) == 0)
2275     return TRUE;
2276
2277   return FALSE;
2278 }
2279
2280 boolean fileHasSuffix(char *basename, char *suffix)
2281 {
2282   static char *basename_lower = NULL;
2283   int basename_length, suffix_length;
2284
2285   checked_free(basename_lower);
2286
2287   if (basename == NULL || suffix == NULL)
2288     return FALSE;
2289
2290   basename_lower = getStringToLower(basename);
2291   basename_length = strlen(basename_lower);
2292   suffix_length = strlen(suffix);
2293
2294   if (basename_length > suffix_length + 1 &&
2295       basename_lower[basename_length - suffix_length - 1] == '.' &&
2296       strEqual(&basename_lower[basename_length - suffix_length], suffix))
2297     return TRUE;
2298
2299   return FALSE;
2300 }
2301
2302 static boolean FileCouldBeArtwork(char *filename)
2303 {
2304   char *basename = getBaseNamePtr(filename);
2305
2306   return (!strEqual(basename, ".") &&
2307           !strEqual(basename, "..") &&
2308           !fileHasSuffix(basename, "txt") &&
2309           !fileHasSuffix(basename, "conf") &&
2310           !directoryExists(filename));
2311 }
2312
2313 boolean FileIsGraphic(char *filename)
2314 {
2315   return FileCouldBeArtwork(filename);
2316 }
2317
2318 boolean FileIsSound(char *filename)
2319 {
2320   return FileCouldBeArtwork(filename);
2321 }
2322
2323 boolean FileIsMusic(char *filename)
2324 {
2325   return FileCouldBeArtwork(filename);
2326 }
2327
2328 boolean FileIsArtworkType(char *filename, int type)
2329 {
2330   if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
2331       (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
2332       (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
2333     return TRUE;
2334
2335   return FALSE;
2336 }
2337
2338 /* ------------------------------------------------------------------------- */
2339 /* functions for loading artwork configuration information                   */
2340 /* ------------------------------------------------------------------------- */
2341
2342 char *get_mapped_token(char *token)
2343 {
2344   /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
2345   static char *map_token_prefix[][2] =
2346   {
2347     { "char_procent",           "char_percent"  },
2348     { NULL,                                     }
2349   };
2350   int i;
2351
2352   for (i = 0; map_token_prefix[i][0] != NULL; i++)
2353   {
2354     int len_token_prefix = strlen(map_token_prefix[i][0]);
2355
2356     if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
2357       return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
2358   }
2359
2360   return NULL;
2361 }
2362
2363 /* This function checks if a string <s> of the format "string1, string2, ..."
2364    exactly contains a string <s_contained>. */
2365
2366 static boolean string_has_parameter(char *s, char *s_contained)
2367 {
2368   char *substring;
2369
2370   if (s == NULL || s_contained == NULL)
2371     return FALSE;
2372
2373   if (strlen(s_contained) > strlen(s))
2374     return FALSE;
2375
2376   if (strncmp(s, s_contained, strlen(s_contained)) == 0)
2377   {
2378     char next_char = s[strlen(s_contained)];
2379
2380     /* check if next character is delimiter or whitespace */
2381     return (next_char == ',' || next_char == '\0' ||
2382             next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
2383   }
2384
2385   /* check if string contains another parameter string after a comma */
2386   substring = strchr(s, ',');
2387   if (substring == NULL)        /* string does not contain a comma */
2388     return FALSE;
2389
2390   /* advance string pointer to next character after the comma */
2391   substring++;
2392
2393   /* skip potential whitespaces after the comma */
2394   while (*substring == ' ' || *substring == '\t')
2395     substring++;
2396
2397   return string_has_parameter(substring, s_contained);
2398 }
2399
2400 int get_parameter_value(char *value_raw, char *suffix, int type)
2401 {
2402   char *value = getStringToLower(value_raw);
2403   int result = 0;       /* probably a save default value */
2404
2405   if (strEqual(suffix, ".direction"))
2406   {
2407     result = (strEqual(value, "left")  ? MV_LEFT :
2408               strEqual(value, "right") ? MV_RIGHT :
2409               strEqual(value, "up")    ? MV_UP :
2410               strEqual(value, "down")  ? MV_DOWN : MV_NONE);
2411   }
2412   else if (strEqual(suffix, ".align"))
2413   {
2414     result = (strEqual(value, "left")   ? ALIGN_LEFT :
2415               strEqual(value, "right")  ? ALIGN_RIGHT :
2416               strEqual(value, "center") ? ALIGN_CENTER :
2417               strEqual(value, "middle") ? ALIGN_CENTER : ALIGN_DEFAULT);
2418   }
2419   else if (strEqual(suffix, ".valign"))
2420   {
2421     result = (strEqual(value, "top")    ? VALIGN_TOP :
2422               strEqual(value, "bottom") ? VALIGN_BOTTOM :
2423               strEqual(value, "middle") ? VALIGN_MIDDLE :
2424               strEqual(value, "center") ? VALIGN_MIDDLE : VALIGN_DEFAULT);
2425   }
2426   else if (strEqual(suffix, ".anim_mode"))
2427   {
2428     result = (string_has_parameter(value, "none")       ? ANIM_NONE :
2429               string_has_parameter(value, "loop")       ? ANIM_LOOP :
2430               string_has_parameter(value, "linear")     ? ANIM_LINEAR :
2431               string_has_parameter(value, "pingpong")   ? ANIM_PINGPONG :
2432               string_has_parameter(value, "pingpong2")  ? ANIM_PINGPONG2 :
2433               string_has_parameter(value, "random")     ? ANIM_RANDOM :
2434               string_has_parameter(value, "ce_value")   ? ANIM_CE_VALUE :
2435               string_has_parameter(value, "ce_score")   ? ANIM_CE_SCORE :
2436               string_has_parameter(value, "ce_delay")   ? ANIM_CE_DELAY :
2437               string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
2438               string_has_parameter(value, "vertical")   ? ANIM_VERTICAL :
2439               string_has_parameter(value, "centered")   ? ANIM_CENTERED :
2440               ANIM_DEFAULT);
2441
2442     if (string_has_parameter(value, "reverse"))
2443       result |= ANIM_REVERSE;
2444
2445     if (string_has_parameter(value, "opaque_player"))
2446       result |= ANIM_OPAQUE_PLAYER;
2447
2448     if (string_has_parameter(value, "static_panel"))
2449       result |= ANIM_STATIC_PANEL;
2450   }
2451   else if (strEqual(suffix, ".class"))
2452   {
2453     result = get_hash_from_key(value);
2454   }
2455   else if (strEqual(suffix, ".style"))
2456   {
2457     result = STYLE_DEFAULT;
2458
2459     if (string_has_parameter(value, "accurate_borders"))
2460       result |= STYLE_ACCURATE_BORDERS;
2461
2462     if (string_has_parameter(value, "inner_corners"))
2463       result |= STYLE_INNER_CORNERS;
2464   }
2465   else if (strEqual(suffix, ".fade_mode"))
2466   {
2467     result = (string_has_parameter(value, "none")       ? FADE_MODE_NONE :
2468               string_has_parameter(value, "fade")       ? FADE_MODE_FADE :
2469               string_has_parameter(value, "crossfade")  ? FADE_MODE_CROSSFADE :
2470               string_has_parameter(value, "melt")       ? FADE_MODE_MELT :
2471               FADE_MODE_DEFAULT);
2472   }
2473   else if (strPrefix(suffix, ".font"))          /* (may also be ".font_xyz") */
2474   {
2475     result = gfx.get_font_from_token_function(value);
2476   }
2477   else          /* generic parameter of type integer or boolean */
2478   {
2479     result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2480               type == TYPE_INTEGER ? get_integer_from_string(value) :
2481               type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
2482               ARG_UNDEFINED_VALUE);
2483   }
2484
2485   free(value);
2486
2487   return result;
2488 }
2489
2490 struct ScreenModeInfo *get_screen_mode_from_string(char *screen_mode_string)
2491 {
2492   static struct ScreenModeInfo screen_mode;
2493   char *screen_mode_string_x = strchr(screen_mode_string, 'x');
2494   char *screen_mode_string_copy;
2495   char *screen_mode_string_pos_w;
2496   char *screen_mode_string_pos_h;
2497
2498   if (screen_mode_string_x == NULL)     /* invalid screen mode format */
2499     return NULL;
2500
2501   screen_mode_string_copy = getStringCopy(screen_mode_string);
2502
2503   screen_mode_string_pos_w = screen_mode_string_copy;
2504   screen_mode_string_pos_h = strchr(screen_mode_string_copy, 'x');
2505   *screen_mode_string_pos_h++ = '\0';
2506
2507   screen_mode.width  = atoi(screen_mode_string_pos_w);
2508   screen_mode.height = atoi(screen_mode_string_pos_h);
2509
2510   return &screen_mode;
2511 }
2512
2513 void get_aspect_ratio_from_screen_mode(struct ScreenModeInfo *screen_mode,
2514                                        int *x, int *y)
2515 {
2516   float aspect_ratio = (float)screen_mode->width / (float)screen_mode->height;
2517   float aspect_ratio_new;
2518   int i = 1;
2519
2520   do
2521   {
2522     *x = i * aspect_ratio + 0.000001;
2523     *y = i;
2524
2525     aspect_ratio_new = (float)*x / (float)*y;
2526
2527     i++;
2528   }
2529   while (aspect_ratio_new != aspect_ratio && *y < screen_mode->height);
2530 }
2531
2532 static void FreeCustomArtworkList(struct ArtworkListInfo *,
2533                                   struct ListNodeInfo ***, int *);
2534
2535 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2536                                            struct ConfigTypeInfo *suffix_list,
2537                                            char **ignore_tokens,
2538                                            int num_file_list_entries)
2539 {
2540   struct FileInfo *file_list;
2541   int num_file_list_entries_found = 0;
2542   int num_suffix_list_entries = 0;
2543   int list_pos;
2544   int i, j;
2545
2546   file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2547
2548   for (i = 0; suffix_list[i].token != NULL; i++)
2549     num_suffix_list_entries++;
2550
2551   /* always start with reliable default values */
2552   for (i = 0; i < num_file_list_entries; i++)
2553   {
2554     file_list[i].token = NULL;
2555
2556     file_list[i].default_filename = NULL;
2557     file_list[i].filename = NULL;
2558
2559     if (num_suffix_list_entries > 0)
2560     {
2561       int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2562
2563       file_list[i].default_parameter = checked_calloc(parameter_array_size);
2564       file_list[i].parameter = checked_calloc(parameter_array_size);
2565
2566       for (j = 0; j < num_suffix_list_entries; j++)
2567       {
2568         setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2569         setString(&file_list[i].parameter[j], suffix_list[j].value);
2570       }
2571
2572       file_list[i].redefined = FALSE;
2573       file_list[i].fallback_to_default = FALSE;
2574       file_list[i].default_is_cloned = FALSE;
2575     }
2576   }
2577
2578   list_pos = 0;
2579
2580   for (i = 0; config_list[i].token != NULL; i++)
2581   {
2582     int len_config_token = strlen(config_list[i].token);
2583     boolean is_file_entry = TRUE;
2584
2585     for (j = 0; suffix_list[j].token != NULL; j++)
2586     {
2587       int len_suffix = strlen(suffix_list[j].token);
2588
2589       if (len_suffix < len_config_token &&
2590           strEqual(&config_list[i].token[len_config_token - len_suffix],
2591                    suffix_list[j].token))
2592       {
2593         setString(&file_list[list_pos].default_parameter[j],
2594                   config_list[i].value);
2595
2596         is_file_entry = FALSE;
2597
2598         break;
2599       }
2600     }
2601
2602     /* the following tokens are no file definitions, but other config tokens */
2603     for (j = 0; ignore_tokens[j] != NULL; j++)
2604       if (strEqual(config_list[i].token, ignore_tokens[j]))
2605         is_file_entry = FALSE;
2606
2607     if (is_file_entry)
2608     {
2609       if (i > 0)
2610         list_pos++;
2611
2612       if (list_pos >= num_file_list_entries)
2613         break;
2614
2615       file_list[list_pos].token = config_list[i].token;
2616       file_list[list_pos].default_filename = config_list[i].value;
2617     }
2618
2619     if (strSuffix(config_list[i].token, ".clone_from"))
2620       file_list[list_pos].default_is_cloned = TRUE;
2621   }
2622
2623   num_file_list_entries_found = list_pos + 1;
2624   if (num_file_list_entries_found != num_file_list_entries)
2625   {
2626     Error(ERR_INFO_LINE, "-");
2627     Error(ERR_INFO, "inconsistant config list information:");
2628     Error(ERR_INFO, "- should be:   %d (according to 'src/conf_xxx.h')",
2629           num_file_list_entries);
2630     Error(ERR_INFO, "- found to be: %d (according to 'src/conf_xxx.c')",
2631           num_file_list_entries_found);
2632     Error(ERR_EXIT,   "please fix");
2633   }
2634
2635   return file_list;
2636 }
2637
2638 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
2639 {
2640   int len_token = strlen(token);
2641   int len_suffix = strlen(suffix);
2642
2643   if (start_pos < 0)    /* compare suffix from end of string */
2644     start_pos += len_token;
2645
2646   if (start_pos < 0 || start_pos + len_suffix > len_token)
2647     return FALSE;
2648
2649   if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
2650     return FALSE;
2651
2652   if (token[start_pos + len_suffix] == '\0')
2653     return TRUE;
2654
2655   if (token[start_pos + len_suffix] == '.')
2656     return TRUE;
2657
2658   return FALSE;
2659 }
2660
2661 #define KNOWN_TOKEN_VALUE       "[KNOWN_TOKEN_VALUE]"
2662
2663 static void read_token_parameters(SetupFileHash *setup_file_hash,
2664                                   struct ConfigTypeInfo *suffix_list,
2665                                   struct FileInfo *file_list_entry)
2666 {
2667   /* check for config token that is the base token without any suffixes */
2668   char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
2669   char *known_token_value = KNOWN_TOKEN_VALUE;
2670   int i;
2671
2672   if (filename != NULL)
2673   {
2674     setString(&file_list_entry->filename, filename);
2675
2676     /* when file definition found, set all parameters to default values */
2677     for (i = 0; suffix_list[i].token != NULL; i++)
2678       setString(&file_list_entry->parameter[i], suffix_list[i].value);
2679
2680     file_list_entry->redefined = TRUE;
2681
2682     /* mark config file token as well known from default config */
2683     setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
2684   }
2685
2686   /* check for config tokens that can be build by base token and suffixes */
2687   for (i = 0; suffix_list[i].token != NULL; i++)
2688   {
2689     char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
2690     char *value = getHashEntry(setup_file_hash, token);
2691
2692     if (value != NULL)
2693     {
2694       setString(&file_list_entry->parameter[i], value);
2695
2696       /* mark config file token as well known from default config */
2697       setHashEntry(setup_file_hash, token, known_token_value);
2698     }
2699
2700     free(token);
2701   }
2702 }
2703
2704 static void add_dynamic_file_list_entry(struct FileInfo **list,
2705                                         int *num_list_entries,
2706                                         SetupFileHash *extra_file_hash,
2707                                         struct ConfigTypeInfo *suffix_list,
2708                                         int num_suffix_list_entries,
2709                                         char *token)
2710 {
2711   struct FileInfo *new_list_entry;
2712   int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2713
2714   (*num_list_entries)++;
2715   *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
2716   new_list_entry = &(*list)[*num_list_entries - 1];
2717
2718   new_list_entry->token = getStringCopy(token);
2719   new_list_entry->default_filename = NULL;
2720   new_list_entry->filename = NULL;
2721   new_list_entry->parameter = checked_calloc(parameter_array_size);
2722
2723   new_list_entry->redefined = FALSE;
2724   new_list_entry->fallback_to_default = FALSE;
2725   new_list_entry->default_is_cloned = FALSE;
2726
2727   read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
2728 }
2729
2730 static void add_property_mapping(struct PropertyMapping **list,
2731                                  int *num_list_entries,
2732                                  int base_index, int ext1_index,
2733                                  int ext2_index, int ext3_index,
2734                                  int artwork_index)
2735 {
2736   struct PropertyMapping *new_list_entry;
2737
2738   (*num_list_entries)++;
2739   *list = checked_realloc(*list,
2740                           *num_list_entries * sizeof(struct PropertyMapping));
2741   new_list_entry = &(*list)[*num_list_entries - 1];
2742
2743   new_list_entry->base_index = base_index;
2744   new_list_entry->ext1_index = ext1_index;
2745   new_list_entry->ext2_index = ext2_index;
2746   new_list_entry->ext3_index = ext3_index;
2747
2748   new_list_entry->artwork_index = artwork_index;
2749 }
2750
2751 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
2752                                           char *filename)
2753 {
2754   struct FileInfo *file_list = artwork_info->file_list;
2755   struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2756   char **base_prefixes = artwork_info->base_prefixes;
2757   char **ext1_suffixes = artwork_info->ext1_suffixes;
2758   char **ext2_suffixes = artwork_info->ext2_suffixes;
2759   char **ext3_suffixes = artwork_info->ext3_suffixes;
2760   char **ignore_tokens = artwork_info->ignore_tokens;
2761   int num_file_list_entries = artwork_info->num_file_list_entries;
2762   int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
2763   int num_base_prefixes = artwork_info->num_base_prefixes;
2764   int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
2765   int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
2766   int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
2767   int num_ignore_tokens = artwork_info->num_ignore_tokens;
2768   SetupFileHash *setup_file_hash, *valid_file_hash;
2769   SetupFileHash *extra_file_hash, *empty_file_hash;
2770   char *known_token_value = KNOWN_TOKEN_VALUE;
2771   int i, j, k, l;
2772
2773   if (filename == NULL)
2774     return;
2775
2776   if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
2777     return;
2778
2779   /* separate valid (defined) from empty (undefined) config token values */
2780   valid_file_hash = newSetupFileHash();
2781   empty_file_hash = newSetupFileHash();
2782   BEGIN_HASH_ITERATION(setup_file_hash, itr)
2783   {
2784     char *value = HASH_ITERATION_VALUE(itr);
2785
2786     setHashEntry(*value ? valid_file_hash : empty_file_hash,
2787                  HASH_ITERATION_TOKEN(itr), value);
2788   }
2789   END_HASH_ITERATION(setup_file_hash, itr)
2790
2791   /* at this point, we do not need the setup file hash anymore -- free it */
2792   freeSetupFileHash(setup_file_hash);
2793
2794   /* map deprecated to current tokens (using prefix match and replace) */
2795   BEGIN_HASH_ITERATION(valid_file_hash, itr)
2796   {
2797     char *token = HASH_ITERATION_TOKEN(itr);
2798     char *mapped_token = get_mapped_token(token);
2799
2800     if (mapped_token != NULL)
2801     {
2802       char *value = HASH_ITERATION_VALUE(itr);
2803
2804       /* add mapped token */
2805       setHashEntry(valid_file_hash, mapped_token, value);
2806
2807       /* ignore old token (by setting it to "known" keyword) */
2808       setHashEntry(valid_file_hash, token, known_token_value);
2809
2810       free(mapped_token);
2811     }
2812   }
2813   END_HASH_ITERATION(valid_file_hash, itr)
2814
2815   /* read parameters for all known config file tokens */
2816   for (i = 0; i < num_file_list_entries; i++)
2817     read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
2818
2819   /* set all tokens that can be ignored here to "known" keyword */
2820   for (i = 0; i < num_ignore_tokens; i++)
2821     setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
2822
2823   /* copy all unknown config file tokens to extra config hash */
2824   extra_file_hash = newSetupFileHash();
2825   BEGIN_HASH_ITERATION(valid_file_hash, itr)
2826   {
2827     char *value = HASH_ITERATION_VALUE(itr);
2828
2829     if (!strEqual(value, known_token_value))
2830       setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
2831   }
2832   END_HASH_ITERATION(valid_file_hash, itr)
2833
2834   /* at this point, we do not need the valid file hash anymore -- free it */
2835   freeSetupFileHash(valid_file_hash);
2836
2837   /* now try to determine valid, dynamically defined config tokens */
2838
2839   BEGIN_HASH_ITERATION(extra_file_hash, itr)
2840   {
2841     struct FileInfo **dynamic_file_list =
2842       &artwork_info->dynamic_file_list;
2843     int *num_dynamic_file_list_entries =
2844       &artwork_info->num_dynamic_file_list_entries;
2845     struct PropertyMapping **property_mapping =
2846       &artwork_info->property_mapping;
2847     int *num_property_mapping_entries =
2848       &artwork_info->num_property_mapping_entries;
2849     int current_summarized_file_list_entry =
2850       artwork_info->num_file_list_entries +
2851       artwork_info->num_dynamic_file_list_entries;
2852     char *token = HASH_ITERATION_TOKEN(itr);
2853     int len_token = strlen(token);
2854     int start_pos;
2855     boolean base_prefix_found = FALSE;
2856     boolean parameter_suffix_found = FALSE;
2857
2858     /* skip all parameter definitions (handled by read_token_parameters()) */
2859     for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
2860     {
2861       int len_suffix = strlen(suffix_list[i].token);
2862
2863       if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
2864         parameter_suffix_found = TRUE;
2865     }
2866
2867     if (parameter_suffix_found)
2868       continue;
2869
2870     /* ---------- step 0: search for matching base prefix ---------- */
2871
2872     start_pos = 0;
2873     for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
2874     {
2875       char *base_prefix = base_prefixes[i];
2876       int len_base_prefix = strlen(base_prefix);
2877       boolean ext1_suffix_found = FALSE;
2878       boolean ext2_suffix_found = FALSE;
2879       boolean ext3_suffix_found = FALSE;
2880       boolean exact_match = FALSE;
2881       int base_index = -1;
2882       int ext1_index = -1;
2883       int ext2_index = -1;
2884       int ext3_index = -1;
2885
2886       base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
2887
2888       if (!base_prefix_found)
2889         continue;
2890
2891       base_index = i;
2892
2893       if (start_pos + len_base_prefix == len_token)     /* exact match */
2894       {
2895         exact_match = TRUE;
2896
2897         add_dynamic_file_list_entry(dynamic_file_list,
2898                                     num_dynamic_file_list_entries,
2899                                     extra_file_hash,
2900                                     suffix_list,
2901                                     num_suffix_list_entries,
2902                                     token);
2903         add_property_mapping(property_mapping,
2904                              num_property_mapping_entries,
2905                              base_index, -1, -1, -1,
2906                              current_summarized_file_list_entry);
2907         continue;
2908       }
2909
2910       /* ---------- step 1: search for matching first suffix ---------- */
2911
2912       start_pos += len_base_prefix;
2913       for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
2914       {
2915         char *ext1_suffix = ext1_suffixes[j];
2916         int len_ext1_suffix = strlen(ext1_suffix);
2917
2918         ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
2919
2920         if (!ext1_suffix_found)
2921           continue;
2922
2923         ext1_index = j;
2924
2925         if (start_pos + len_ext1_suffix == len_token)   /* exact match */
2926         {
2927           exact_match = TRUE;
2928
2929           add_dynamic_file_list_entry(dynamic_file_list,
2930                                       num_dynamic_file_list_entries,
2931                                       extra_file_hash,
2932                                       suffix_list,
2933                                       num_suffix_list_entries,
2934                                       token);
2935           add_property_mapping(property_mapping,
2936                                num_property_mapping_entries,
2937                                base_index, ext1_index, -1, -1,
2938                                current_summarized_file_list_entry);
2939           continue;
2940         }
2941
2942         start_pos += len_ext1_suffix;
2943       }
2944
2945       if (exact_match)
2946         break;
2947
2948       /* ---------- step 2: search for matching second suffix ---------- */
2949
2950       for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
2951       {
2952         char *ext2_suffix = ext2_suffixes[k];
2953         int len_ext2_suffix = strlen(ext2_suffix);
2954
2955         ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
2956
2957         if (!ext2_suffix_found)
2958           continue;
2959
2960         ext2_index = k;
2961
2962         if (start_pos + len_ext2_suffix == len_token)   /* exact match */
2963         {
2964           exact_match = TRUE;
2965
2966           add_dynamic_file_list_entry(dynamic_file_list,
2967                                       num_dynamic_file_list_entries,
2968                                       extra_file_hash,
2969                                       suffix_list,
2970                                       num_suffix_list_entries,
2971                                       token);
2972           add_property_mapping(property_mapping,
2973                                num_property_mapping_entries,
2974                                base_index, ext1_index, ext2_index, -1,
2975                                current_summarized_file_list_entry);
2976           continue;
2977         }
2978
2979         start_pos += len_ext2_suffix;
2980       }
2981
2982       if (exact_match)
2983         break;
2984
2985       /* ---------- step 3: search for matching third suffix ---------- */
2986
2987       for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
2988       {
2989         char *ext3_suffix = ext3_suffixes[l];
2990         int len_ext3_suffix = strlen(ext3_suffix);
2991
2992         ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
2993
2994         if (!ext3_suffix_found)
2995           continue;
2996
2997         ext3_index = l;
2998
2999         if (start_pos + len_ext3_suffix == len_token) /* exact match */
3000         {
3001           exact_match = TRUE;
3002
3003           add_dynamic_file_list_entry(dynamic_file_list,
3004                                       num_dynamic_file_list_entries,
3005                                       extra_file_hash,
3006                                       suffix_list,
3007                                       num_suffix_list_entries,
3008                                       token);
3009           add_property_mapping(property_mapping,
3010                                num_property_mapping_entries,
3011                                base_index, ext1_index, ext2_index, ext3_index,
3012                                current_summarized_file_list_entry);
3013           continue;
3014         }
3015       }
3016     }
3017   }
3018   END_HASH_ITERATION(extra_file_hash, itr)
3019
3020   if (artwork_info->num_dynamic_file_list_entries > 0)
3021   {
3022     artwork_info->dynamic_artwork_list =
3023       checked_calloc(artwork_info->num_dynamic_file_list_entries *
3024                      artwork_info->sizeof_artwork_list_entry);
3025   }
3026
3027   if (options.verbose && IS_PARENT_PROCESS())
3028   {
3029     SetupFileList *setup_file_list, *list;
3030     boolean dynamic_tokens_found = FALSE;
3031     boolean unknown_tokens_found = FALSE;
3032     boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3033
3034     if ((setup_file_list = loadSetupFileList(filename)) == NULL)
3035       Error(ERR_EXIT, "loadSetupFileHash works, but loadSetupFileList fails");
3036
3037     BEGIN_HASH_ITERATION(extra_file_hash, itr)
3038     {
3039       if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3040         dynamic_tokens_found = TRUE;
3041       else
3042         unknown_tokens_found = TRUE;
3043     }
3044     END_HASH_ITERATION(extra_file_hash, itr)
3045
3046     if (options.debug && dynamic_tokens_found)
3047     {
3048       Error(ERR_INFO_LINE, "-");
3049       Error(ERR_INFO, "dynamic token(s) found in config file:");
3050       Error(ERR_INFO, "- config file: '%s'", filename);
3051
3052       for (list = setup_file_list; list != NULL; list = list->next)
3053       {
3054         char *value = getHashEntry(extra_file_hash, list->token);
3055
3056         if (value != NULL && strEqual(value, known_token_value))
3057           Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3058       }
3059
3060       Error(ERR_INFO_LINE, "-");
3061     }
3062
3063     if (unknown_tokens_found)
3064     {
3065       Error(ERR_INFO_LINE, "-");
3066       Error(ERR_INFO, "warning: unknown token(s) found in config file:");
3067       Error(ERR_INFO, "- config file: '%s'", filename);
3068
3069       for (list = setup_file_list; list != NULL; list = list->next)
3070       {
3071         char *value = getHashEntry(extra_file_hash, list->token);
3072
3073         if (value != NULL && !strEqual(value, known_token_value))
3074           Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3075       }
3076
3077       Error(ERR_INFO_LINE, "-");
3078     }
3079
3080     if (undefined_values_found)
3081     {
3082       Error(ERR_INFO_LINE, "-");
3083       Error(ERR_INFO, "warning: undefined values found in config file:");
3084       Error(ERR_INFO, "- config file: '%s'", filename);
3085
3086       for (list = setup_file_list; list != NULL; list = list->next)
3087       {
3088         char *value = getHashEntry(empty_file_hash, list->token);
3089
3090         if (value != NULL)
3091           Error(ERR_INFO, "- undefined value for token: '%s'", list->token);
3092       }
3093
3094       Error(ERR_INFO_LINE, "-");
3095     }
3096
3097     freeSetupFileList(setup_file_list);
3098   }
3099
3100   freeSetupFileHash(extra_file_hash);
3101   freeSetupFileHash(empty_file_hash);
3102 }
3103
3104 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3105 {
3106   struct FileInfo *file_list = artwork_info->file_list;
3107   int num_file_list_entries = artwork_info->num_file_list_entries;
3108   int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3109   char *filename_base = UNDEFINED_FILENAME, *filename_local;
3110   int i, j;
3111
3112   DrawInitText("Loading artwork config", 120, FC_GREEN);
3113   DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
3114
3115   /* always start with reliable default values */
3116   for (i = 0; i < num_file_list_entries; i++)
3117   {
3118     setString(&file_list[i].filename, file_list[i].default_filename);
3119
3120     for (j = 0; j < num_suffix_list_entries; j++)
3121       setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3122
3123     file_list[i].redefined = FALSE;
3124     file_list[i].fallback_to_default = FALSE;
3125   }
3126
3127   /* free previous dynamic artwork file array */
3128   if (artwork_info->dynamic_file_list != NULL)
3129   {
3130     for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3131     {
3132       free(artwork_info->dynamic_file_list[i].token);
3133       free(artwork_info->dynamic_file_list[i].filename);
3134       free(artwork_info->dynamic_file_list[i].parameter);
3135     }
3136
3137     free(artwork_info->dynamic_file_list);
3138     artwork_info->dynamic_file_list = NULL;
3139
3140     FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3141                           &artwork_info->num_dynamic_file_list_entries);
3142   }
3143
3144   /* free previous property mapping */
3145   if (artwork_info->property_mapping != NULL)
3146   {
3147     free(artwork_info->property_mapping);
3148
3149     artwork_info->property_mapping = NULL;
3150     artwork_info->num_property_mapping_entries = 0;
3151   }
3152
3153   if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3154   {
3155     /* first look for special artwork configured in level series config */
3156     filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3157
3158     if (fileExists(filename_base))
3159       LoadArtworkConfigFromFilename(artwork_info, filename_base);
3160   }
3161
3162   filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3163
3164   if (filename_local != NULL && !strEqual(filename_base, filename_local))
3165     LoadArtworkConfigFromFilename(artwork_info, filename_local);
3166 }
3167
3168 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3169                                    struct ListNodeInfo **listnode)
3170 {
3171   if (*listnode)
3172   {
3173     char *filename = (*listnode)->source_filename;
3174
3175     if (--(*listnode)->num_references <= 0)
3176       deleteNodeFromList(&artwork_info->content_list, filename,
3177                          artwork_info->free_artwork);
3178
3179     *listnode = NULL;
3180   }
3181 }
3182
3183 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3184                                     struct ListNodeInfo **listnode,
3185                                     struct FileInfo *file_list_entry)
3186 {
3187   char *init_text[] =
3188   {
3189     "Loading graphics",
3190     "Loading sounds",
3191     "Loading music"
3192   };
3193
3194   ListNode *node;
3195   char *basename = file_list_entry->filename;
3196   char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3197
3198   if (filename == NULL)
3199   {
3200     Error(ERR_WARN, "cannot find artwork file '%s'", basename);
3201
3202     basename = file_list_entry->default_filename;
3203
3204     /* fail for cloned default artwork that has no default filename defined */
3205     if (file_list_entry->default_is_cloned &&
3206         strEqual(basename, UNDEFINED_FILENAME))
3207     {
3208       int error_mode = ERR_WARN;
3209
3210       /* we can get away without sounds and music, but not without graphics */
3211       if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3212         error_mode = ERR_EXIT;
3213
3214       Error(error_mode, "token '%s' was cloned and has no default filename",
3215             file_list_entry->token);
3216
3217       return;
3218     }
3219
3220     /* dynamic artwork has no default filename / skip empty default artwork */
3221     if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3222       return;
3223
3224     file_list_entry->fallback_to_default = TRUE;
3225
3226     Error(ERR_WARN, "trying default artwork file '%s'", basename);
3227
3228     filename = getCustomArtworkFilename(basename, artwork_info->type);
3229
3230     if (filename == NULL)
3231     {
3232       int error_mode = ERR_WARN;
3233
3234       /* we can get away without sounds and music, but not without graphics */
3235       if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3236         error_mode = ERR_EXIT;
3237
3238       Error(error_mode, "cannot find default artwork file '%s'", basename);
3239
3240       return;
3241     }
3242   }
3243
3244   /* check if the old and the new artwork file are the same */
3245   if (*listnode && strEqual((*listnode)->source_filename, filename))
3246   {
3247     /* The old and new artwork are the same (have the same filename and path).
3248        This usually means that this artwork does not exist in this artwork set
3249        and a fallback to the existing artwork is done. */
3250
3251     return;
3252   }
3253
3254   /* delete existing artwork file entry */
3255   deleteArtworkListEntry(artwork_info, listnode);
3256
3257   /* check if the new artwork file already exists in the list of artwork */
3258   if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3259   {
3260       *listnode = (struct ListNodeInfo *)node->content;
3261       (*listnode)->num_references++;
3262
3263       return;
3264   }
3265
3266   DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
3267   DrawInitText(basename, 150, FC_YELLOW);
3268
3269   if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3270   {
3271     /* add new artwork file entry to the list of artwork files */
3272     (*listnode)->num_references = 1;
3273     addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3274                   *listnode);
3275   }
3276   else
3277   {
3278     int error_mode = ERR_WARN;
3279
3280     /* we can get away without sounds and music, but not without graphics */
3281     if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3282       error_mode = ERR_EXIT;
3283
3284     Error(error_mode, "cannot load artwork file '%s'", basename);
3285
3286     return;
3287   }
3288 }
3289
3290 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3291                               struct ListNodeInfo **listnode,
3292                               struct FileInfo *file_list_entry)
3293 {
3294   if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3295   {
3296     deleteArtworkListEntry(artwork_info, listnode);
3297
3298     return;
3299   }
3300
3301   replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3302 }
3303
3304 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3305 {
3306   struct FileInfo *file_list = artwork_info->file_list;
3307   struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3308   int num_file_list_entries = artwork_info->num_file_list_entries;
3309   int num_dynamic_file_list_entries =
3310     artwork_info->num_dynamic_file_list_entries;
3311   int i;
3312
3313   print_timestamp_init("ReloadCustomArtworkList");
3314
3315   for (i = 0; i < num_file_list_entries; i++)
3316     LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3317                       &file_list[i]);
3318
3319   for (i = 0; i < num_dynamic_file_list_entries; i++)
3320     LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3321                       &dynamic_file_list[i]);
3322
3323   print_timestamp_done("ReloadCustomArtworkList");
3324
3325 #if 0
3326   dumpList(artwork_info->content_list);
3327 #endif
3328 }
3329
3330 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
3331                                   struct ListNodeInfo ***list,
3332                                   int *num_list_entries)
3333 {
3334   int i;
3335
3336   if (*list == NULL)
3337     return;
3338
3339   for (i = 0; i < *num_list_entries; i++)
3340     deleteArtworkListEntry(artwork_info, &(*list)[i]);
3341   free(*list);
3342
3343   *list = NULL;
3344   *num_list_entries = 0;
3345 }
3346
3347 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
3348 {
3349   if (artwork_info == NULL)
3350     return;
3351
3352   FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
3353                         &artwork_info->num_file_list_entries);
3354
3355   FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3356                         &artwork_info->num_dynamic_file_list_entries);
3357 }
3358
3359
3360 /* ------------------------------------------------------------------------- */
3361 /* functions only needed for non-Unix (non-command-line) systems             */
3362 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt")    */
3363 /* (now also added for Windows, to create files in user data directory)      */
3364 /* ------------------------------------------------------------------------- */
3365
3366 char *getErrorFilename(char *basename)
3367 {
3368   return getPath2(getUserGameDataDir(), basename);
3369 }
3370
3371 void openErrorFile()
3372 {
3373   InitUserDataDirectory();
3374
3375   if ((program.error_file = fopen(program.error_filename, MODE_WRITE)) == NULL)
3376   {
3377     program.error_file = stderr;
3378
3379     Error(ERR_WARN, "cannot open file '%s' for writing: %s",
3380           program.error_filename, strerror(errno));
3381   }
3382
3383   /* error output should be unbuffered so it is not truncated in a crash */
3384   setbuf(program.error_file, NULL);
3385 }
3386
3387 void closeErrorFile()
3388 {
3389   if (program.error_file != stderr)     /* do not close stream 'stderr' */
3390     fclose(program.error_file);
3391 }
3392
3393 void dumpErrorFile()
3394 {
3395   FILE *error_file = fopen(program.error_filename, MODE_READ);
3396
3397   if (error_file != NULL)
3398   {
3399     while (!feof(error_file))
3400       fputc(fgetc(error_file), stderr);
3401
3402     fclose(error_file);
3403   }
3404 }
3405
3406 void NotifyUserAboutErrorFile()
3407 {
3408 #if defined(PLATFORM_WIN32)
3409   char *title_text = getStringCat2(program.program_title, " Error Message");
3410   char *error_text = getStringCat2("The program was aborted due to an error; "
3411                                    "for details, see the following error file:"
3412                                    STRING_NEWLINE, program.error_filename);
3413
3414   MessageBox(NULL, error_text, title_text, MB_OK);
3415 #endif
3416 }
3417
3418
3419 /* ------------------------------------------------------------------------- */
3420 /* the following is only for debugging purpose and normally not used         */
3421 /* ------------------------------------------------------------------------- */
3422
3423 #if DEBUG
3424
3425 #define DEBUG_PRINT_INIT_TIMESTAMPS             FALSE
3426 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH       10
3427
3428 #define DEBUG_NUM_TIMESTAMPS                    10
3429 #define DEBUG_TIME_IN_MICROSECONDS              0
3430
3431 #if DEBUG_TIME_IN_MICROSECONDS
3432 static double Counter_Microseconds()
3433 {
3434   static struct timeval base_time = { 0, 0 };
3435   struct timeval current_time;
3436   double counter;
3437
3438   gettimeofday(&current_time, NULL);
3439
3440   /* reset base time in case of wrap-around */
3441   if (current_time.tv_sec < base_time.tv_sec)
3442     base_time = current_time;
3443
3444   counter =
3445     ((double)(current_time.tv_sec  - base_time.tv_sec)) * 1000000 +
3446     ((double)(current_time.tv_usec - base_time.tv_usec));
3447
3448   return counter;               /* return microseconds since last init */
3449 }
3450 #endif
3451
3452 char *debug_print_timestamp_get_padding(int padding_size)
3453 {
3454   static char *padding = NULL;
3455   int max_padding_size = 100;
3456
3457   if (padding == NULL)
3458   {
3459     padding = checked_calloc(max_padding_size + 1);
3460     memset(padding, ' ', max_padding_size);
3461   }
3462
3463   return &padding[MAX(0, max_padding_size - padding_size)];
3464 }
3465
3466 void debug_print_timestamp(int counter_nr, char *message)
3467 {
3468   int indent_size = 8;
3469   int padding_size = 40;
3470   float timestamp_interval;
3471
3472   if (counter_nr < 0)
3473     Error(ERR_EXIT, "debugging: invalid negative counter");
3474   else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
3475     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
3476
3477 #if DEBUG_TIME_IN_MICROSECONDS
3478   static double counter[DEBUG_NUM_TIMESTAMPS][2];
3479   char *unit = "ms";
3480
3481   counter[counter_nr][0] = Counter_Microseconds();
3482 #else
3483   static int counter[DEBUG_NUM_TIMESTAMPS][2];
3484   char *unit = "s";
3485
3486   counter[counter_nr][0] = Counter();
3487 #endif
3488
3489   timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
3490   counter[counter_nr][1] = counter[counter_nr][0];
3491
3492   if (message)
3493     Error(ERR_DEBUG, "%s%s%s %.3f %s",
3494            debug_print_timestamp_get_padding(counter_nr * indent_size),
3495            message,
3496            debug_print_timestamp_get_padding(padding_size - strlen(message)),
3497            timestamp_interval / 1000,
3498            unit);
3499 }
3500
3501 void debug_print_parent_only(char *format, ...)
3502 {
3503   if (!IS_PARENT_PROCESS())
3504     return;
3505
3506   if (format)
3507   {
3508     va_list ap;
3509
3510     va_start(ap, format);
3511     vprintf(format, ap);
3512     va_end(ap);
3513
3514     printf("\n");
3515   }
3516 }
3517
3518 #endif  /* DEBUG */
3519
3520 void print_timestamp_ext(char *message, char *mode)
3521 {
3522 #if DEBUG_PRINT_INIT_TIMESTAMPS
3523   static char *debug_message = NULL;
3524   static char *last_message = NULL;
3525   static int counter_nr = 0;
3526   int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
3527
3528   checked_free(debug_message);
3529   debug_message = getStringCat3(mode, " ", message);
3530
3531   if (strEqual(mode, "INIT"))
3532   {
3533     debug_print_timestamp(counter_nr, NULL);
3534
3535     if (counter_nr + 1 < max_depth)
3536       debug_print_timestamp(counter_nr, debug_message);
3537
3538     counter_nr++;
3539
3540     debug_print_timestamp(counter_nr, NULL);
3541   }
3542   else if (strEqual(mode, "DONE"))
3543   {
3544     counter_nr--;
3545
3546     if (counter_nr + 1 < max_depth ||
3547         (counter_nr == 0 && max_depth == 1))
3548     {
3549       last_message = message;
3550
3551       if (counter_nr == 0 && max_depth == 1)
3552       {
3553         checked_free(debug_message);
3554         debug_message = getStringCat3("TIME", " ", message);
3555       }
3556
3557       debug_print_timestamp(counter_nr, debug_message);
3558     }
3559   }
3560   else if (!strEqual(mode, "TIME") ||
3561            !strEqual(message, last_message))
3562   {
3563     if (counter_nr < max_depth)
3564       debug_print_timestamp(counter_nr, debug_message);
3565   }
3566 #endif
3567 }
3568
3569 void print_timestamp_init(char *message)
3570 {
3571   print_timestamp_ext(message, "INIT");
3572 }
3573
3574 void print_timestamp_time(char *message)
3575 {
3576   print_timestamp_ext(message, "TIME");
3577 }
3578
3579 void print_timestamp_done(char *message)
3580 {
3581   print_timestamp_ext(message, "DONE");
3582 }