Merge branch 'convert-src-to-7bit'
[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   options.debug_x11_sync = FALSE;
764
765 #if 1
766   options.verbose = TRUE;
767 #else
768 #if !defined(PLATFORM_UNIX)
769   if (*options_left == NULL)    /* no options given -- enable verbose mode */
770     options.verbose = TRUE;
771 #endif
772 #endif
773
774   while (*options_left)
775   {
776     char option_str[MAX_OPTION_LEN];
777     char *option = options_left[0];
778     char *next_option = options_left[1];
779     char *option_arg = NULL;
780     int option_len = strlen(option);
781
782     if (option_len >= MAX_OPTION_LEN)
783       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
784
785     strcpy(option_str, option);                 /* copy argument into buffer */
786     option = option_str;
787
788     if (strEqual(option, "--"))                 /* stop scanning arguments */
789       break;
790
791     if (strPrefix(option, "--"))                /* treat '--' like '-' */
792       option++;
793
794     option_arg = strchr(option, '=');
795     if (option_arg == NULL)                     /* no '=' in option */
796       option_arg = next_option;
797     else
798     {
799       *option_arg++ = '\0';                     /* cut argument from option */
800       if (*option_arg == '\0')                  /* no argument after '=' */
801         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
802     }
803
804     option_len = strlen(option);
805
806     if (strEqual(option, "-"))
807     {
808       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
809     }
810     else if (strncmp(option, "-help", option_len) == 0)
811     {
812       print_usage_function();
813
814       exit(0);
815     }
816     else if (strncmp(option, "-display", option_len) == 0)
817     {
818       if (option_arg == NULL)
819         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
820
821       options.display_name = option_arg;
822       if (option_arg == next_option)
823         options_left++;
824     }
825     else if (strncmp(option, "-basepath", option_len) == 0)
826     {
827       if (option_arg == NULL)
828         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
829
830       /* this should be extended to separate options for ro and rw data */
831       options.ro_base_directory = ro_base_path = option_arg;
832       options.rw_base_directory = rw_base_path = option_arg;
833       if (option_arg == next_option)
834         options_left++;
835
836       /* adjust paths for sub-directories in base directory accordingly */
837       options.level_directory    = getPath2(ro_base_path, LEVELS_DIRECTORY);
838       options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
839       options.sounds_directory   = getPath2(ro_base_path, SOUNDS_DIRECTORY);
840       options.music_directory    = getPath2(ro_base_path, MUSIC_DIRECTORY);
841       options.docs_directory     = getPath2(ro_base_path, DOCS_DIRECTORY);
842     }
843     else if (strncmp(option, "-levels", option_len) == 0)
844     {
845       if (option_arg == NULL)
846         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
847
848       options.level_directory = option_arg;
849       if (option_arg == next_option)
850         options_left++;
851     }
852     else if (strncmp(option, "-graphics", option_len) == 0)
853     {
854       if (option_arg == NULL)
855         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
856
857       options.graphics_directory = option_arg;
858       if (option_arg == next_option)
859         options_left++;
860     }
861     else if (strncmp(option, "-sounds", option_len) == 0)
862     {
863       if (option_arg == NULL)
864         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
865
866       options.sounds_directory = option_arg;
867       if (option_arg == next_option)
868         options_left++;
869     }
870     else if (strncmp(option, "-music", option_len) == 0)
871     {
872       if (option_arg == NULL)
873         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
874
875       options.music_directory = option_arg;
876       if (option_arg == next_option)
877         options_left++;
878     }
879     else if (strncmp(option, "-network", option_len) == 0)
880     {
881       options.network = TRUE;
882     }
883     else if (strncmp(option, "-serveronly", option_len) == 0)
884     {
885       options.serveronly = TRUE;
886     }
887     else if (strncmp(option, "-debug", option_len) == 0)
888     {
889       options.debug = TRUE;
890     }
891     else if (strncmp(option, "-debug-x11-sync", option_len) == 0)
892     {
893       options.debug_x11_sync = TRUE;
894     }
895     else if (strncmp(option, "-verbose", option_len) == 0)
896     {
897       options.verbose = TRUE;
898     }
899     else if (strncmp(option, "-version", option_len) == 0 ||
900              strncmp(option, "-V", option_len) == 0)
901     {
902       print_version_function();
903
904       exit(0);
905     }
906     else if (strPrefix(option, "-D"))
907     {
908       options.special_flags = getStringCopy(&option[2]);
909     }
910     else if (strncmp(option, "-execute", option_len) == 0)
911     {
912       if (option_arg == NULL)
913         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
914
915       options.execute_command = option_arg;
916       if (option_arg == next_option)
917         options_left++;
918
919       /* when doing batch processing, always enable verbose mode (warnings) */
920       options.verbose = TRUE;
921     }
922     else if (*option == '-')
923     {
924       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
925     }
926     else if (options.server_host == NULL)
927     {
928       options.server_host = *options_left;
929     }
930     else if (options.server_port == 0)
931     {
932       options.server_port = atoi(*options_left);
933       if (options.server_port < 1024)
934         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
935     }
936     else
937       Error(ERR_EXIT_HELP, "too many arguments");
938
939     options_left++;
940   }
941 }
942
943
944 /* ------------------------------------------------------------------------- */
945 /* error handling functions                                                  */
946 /* ------------------------------------------------------------------------- */
947
948 #define MAX_INTERNAL_ERROR_SIZE         1024
949
950 /* used by SetError() and GetError() to store internal error messages */
951 static char internal_error[MAX_INTERNAL_ERROR_SIZE];
952
953 void SetError(char *format, ...)
954 {
955   va_list ap;
956
957   va_start(ap, format);
958   vsnprintf(internal_error, MAX_INTERNAL_ERROR_SIZE, format, ap);
959   va_end(ap);
960 }
961
962 char *GetError()
963 {
964   return internal_error;
965 }
966
967 void Error(int mode, char *format, ...)
968 {
969   static boolean last_line_was_separator = FALSE;
970   char *process_name = "";
971
972 #if defined(PLATFORM_ANDROID)
973   android_log_prio = (mode & ERR_DEBUG ? ANDROID_LOG_DEBUG :
974                       mode & ERR_INFO ? ANDROID_LOG_INFO :
975                       mode & ERR_WARN ? ANDROID_LOG_WARN :
976                       mode & ERR_EXIT ? ANDROID_LOG_FATAL :
977                       ANDROID_LOG_UNKNOWN);
978 #endif
979
980   /* display warnings only when running in verbose mode */
981   if (mode & ERR_WARN && !options.verbose)
982     return;
983
984   if (mode == ERR_INFO_LINE)
985   {
986     if (!last_line_was_separator)
987       fprintf_line(program.error_file, format, 79);
988
989     last_line_was_separator = TRUE;
990
991     return;
992   }
993
994   last_line_was_separator = FALSE;
995
996   if (mode & ERR_SOUND_SERVER)
997     process_name = " sound server";
998   else if (mode & ERR_NETWORK_SERVER)
999     process_name = " network server";
1000   else if (mode & ERR_NETWORK_CLIENT)
1001     process_name = " network client **";
1002
1003   if (format)
1004   {
1005     va_list ap;
1006
1007     fprintf_nonewline(program.error_file, "%s%s: ", program.command_basename,
1008                       process_name);
1009
1010     if (mode & ERR_WARN)
1011       fprintf_nonewline(program.error_file, "warning: ");
1012
1013     va_start(ap, format);
1014     vfprintf_newline(program.error_file, format, ap);
1015     va_end(ap);
1016
1017     if ((mode & ERR_EXIT) && !(mode & ERR_FROM_SERVER))
1018     {
1019       va_start(ap, format);
1020       program.exit_message_function(format, ap);
1021       va_end(ap);
1022     }
1023   }
1024   
1025   if (mode & ERR_HELP)
1026     fprintf_newline(program.error_file,
1027                     "%s: Try option '--help' for more information.",
1028                     program.command_basename);
1029
1030   if (mode & ERR_EXIT)
1031     fprintf_newline(program.error_file, "%s%s: aborting",
1032                     program.command_basename, process_name);
1033
1034   if (mode & ERR_EXIT)
1035   {
1036     if (mode & ERR_FROM_SERVER)
1037       exit(1);                          /* child process: normal exit */
1038     else
1039       program.exit_function(1);         /* main process: clean up stuff */
1040   }
1041 }
1042
1043
1044 /* ------------------------------------------------------------------------- */
1045 /* checked memory allocation and freeing functions                           */
1046 /* ------------------------------------------------------------------------- */
1047
1048 void *checked_malloc(unsigned int size)
1049 {
1050   void *ptr;
1051
1052   ptr = malloc(size);
1053
1054   if (ptr == NULL)
1055     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1056
1057   return ptr;
1058 }
1059
1060 void *checked_calloc(unsigned int size)
1061 {
1062   void *ptr;
1063
1064   ptr = calloc(1, size);
1065
1066   if (ptr == NULL)
1067     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1068
1069   return ptr;
1070 }
1071
1072 void *checked_realloc(void *ptr, unsigned int size)
1073 {
1074   ptr = realloc(ptr, size);
1075
1076   if (ptr == NULL)
1077     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1078
1079   return ptr;
1080 }
1081
1082 void checked_free(void *ptr)
1083 {
1084   if (ptr != NULL)      /* this check should be done by free() anyway */
1085     free(ptr);
1086 }
1087
1088 void clear_mem(void *ptr, unsigned int size)
1089 {
1090 #if defined(PLATFORM_WIN32)
1091   /* for unknown reason, memset() sometimes crashes when compiled with MinGW */
1092   char *cptr = (char *)ptr;
1093
1094   while (size--)
1095     *cptr++ = 0;
1096 #else
1097   memset(ptr, 0, size);
1098 #endif
1099 }
1100
1101
1102 /* ------------------------------------------------------------------------- */
1103 /* various helper functions                                                  */
1104 /* ------------------------------------------------------------------------- */
1105
1106 inline void swap_numbers(int *i1, int *i2)
1107 {
1108   int help = *i1;
1109
1110   *i1 = *i2;
1111   *i2 = help;
1112 }
1113
1114 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1115 {
1116   int help_x = *x1;
1117   int help_y = *y1;
1118
1119   *x1 = *x2;
1120   *x2 = help_x;
1121
1122   *y1 = *y2;
1123   *y2 = help_y;
1124 }
1125
1126 /* the "put" variants of the following file access functions check for the file
1127    pointer being != NULL and return the number of bytes they have or would have
1128    written; this allows for chunk writing functions to first determine the size
1129    of the (not yet written) chunk, write the correct chunk size and finally
1130    write the chunk itself */
1131
1132 int getFile8BitInteger(File *file)
1133 {
1134   return getByteFromFile(file);
1135 }
1136
1137 int putFile8BitInteger(FILE *file, int value)
1138 {
1139   if (file != NULL)
1140     fputc(value, file);
1141
1142   return 1;
1143 }
1144
1145 int getFile16BitInteger(File *file, int byte_order)
1146 {
1147   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1148     return ((getByteFromFile(file) << 8) |
1149             (getByteFromFile(file) << 0));
1150   else           /* BYTE_ORDER_LITTLE_ENDIAN */
1151     return ((getByteFromFile(file) << 0) |
1152             (getByteFromFile(file) << 8));
1153 }
1154
1155 int putFile16BitInteger(FILE *file, int value, int byte_order)
1156 {
1157   if (file != NULL)
1158   {
1159     if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1160     {
1161       fputc((value >> 8) & 0xff, file);
1162       fputc((value >> 0) & 0xff, file);
1163     }
1164     else           /* BYTE_ORDER_LITTLE_ENDIAN */
1165     {
1166       fputc((value >> 0) & 0xff, file);
1167       fputc((value >> 8) & 0xff, file);
1168     }
1169   }
1170
1171   return 2;
1172 }
1173
1174 int getFile32BitInteger(File *file, int byte_order)
1175 {
1176   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1177     return ((getByteFromFile(file) << 24) |
1178             (getByteFromFile(file) << 16) |
1179             (getByteFromFile(file) <<  8) |
1180             (getByteFromFile(file) <<  0));
1181   else           /* BYTE_ORDER_LITTLE_ENDIAN */
1182     return ((getByteFromFile(file) <<  0) |
1183             (getByteFromFile(file) <<  8) |
1184             (getByteFromFile(file) << 16) |
1185             (getByteFromFile(file) << 24));
1186 }
1187
1188 int putFile32BitInteger(FILE *file, int value, int byte_order)
1189 {
1190   if (file != NULL)
1191   {
1192     if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1193     {
1194       fputc((value >> 24) & 0xff, file);
1195       fputc((value >> 16) & 0xff, file);
1196       fputc((value >>  8) & 0xff, file);
1197       fputc((value >>  0) & 0xff, file);
1198     }
1199     else           /* BYTE_ORDER_LITTLE_ENDIAN */
1200     {
1201       fputc((value >>  0) & 0xff, file);
1202       fputc((value >>  8) & 0xff, file);
1203       fputc((value >> 16) & 0xff, file);
1204       fputc((value >> 24) & 0xff, file);
1205     }
1206   }
1207
1208   return 4;
1209 }
1210
1211 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
1212                      int byte_order)
1213 {
1214   const int chunk_name_length = 4;
1215
1216   /* read chunk name */
1217   if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
1218     return FALSE;
1219
1220   if (chunk_size != NULL)
1221   {
1222     /* read chunk size */
1223     *chunk_size = getFile32BitInteger(file, byte_order);
1224   }
1225
1226   return (checkEndOfFile(file) ? FALSE : TRUE);
1227 }
1228
1229 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1230                  int byte_order)
1231 {
1232   int num_bytes = 0;
1233
1234   /* write chunk name */
1235   if (file != NULL)
1236     fputs(chunk_name, file);
1237
1238   num_bytes += strlen(chunk_name);
1239
1240   if (chunk_size >= 0)
1241   {
1242     /* write chunk size */
1243     if (file != NULL)
1244       putFile32BitInteger(file, chunk_size, byte_order);
1245
1246     num_bytes += 4;
1247   }
1248
1249   return num_bytes;
1250 }
1251
1252 int getFileVersion(File *file)
1253 {
1254   int version_major = getByteFromFile(file);
1255   int version_minor = getByteFromFile(file);
1256   int version_patch = getByteFromFile(file);
1257   int version_build = getByteFromFile(file);
1258
1259   return VERSION_IDENT(version_major, version_minor, version_patch,
1260                        version_build);
1261 }
1262
1263 int putFileVersion(FILE *file, int version)
1264 {
1265   if (file != NULL)
1266   {
1267     int version_major = VERSION_MAJOR(version);
1268     int version_minor = VERSION_MINOR(version);
1269     int version_patch = VERSION_PATCH(version);
1270     int version_build = VERSION_BUILD(version);
1271
1272     fputc(version_major, file);
1273     fputc(version_minor, file);
1274     fputc(version_patch, file);
1275     fputc(version_build, file);
1276   }
1277
1278   return 4;
1279 }
1280
1281 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
1282 {
1283   int i;
1284
1285   for (i = 0; i < bytes && !checkEndOfFile(file); i++)
1286     buffer[i] = getByteFromFile(file);
1287 }
1288
1289 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
1290 {
1291   int i;
1292
1293   for(i = 0; i < bytes; i++)
1294     fputc(buffer[i], file);
1295 }
1296
1297 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
1298 {
1299   while (bytes-- && !checkEndOfFile(file))
1300     getByteFromFile(file);
1301 }
1302
1303 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
1304 {
1305   while (bytes--)
1306     fputc(0, file);
1307 }
1308
1309
1310 /* ------------------------------------------------------------------------- */
1311 /* functions to translate key identifiers between different format           */
1312 /* ------------------------------------------------------------------------- */
1313
1314 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
1315 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
1316 #define TRANSLATE_KEYNAME_TO_KEYSYM     2
1317 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  3
1318
1319 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1320 {
1321   static struct
1322   {
1323     Key key;
1324     char *x11name;
1325     char *name;
1326   } translate_key[] =
1327   {
1328     /* normal cursor keys */
1329     { KSYM_Left,        "XK_Left",              "cursor left" },
1330     { KSYM_Right,       "XK_Right",             "cursor right" },
1331     { KSYM_Up,          "XK_Up",                "cursor up" },
1332     { KSYM_Down,        "XK_Down",              "cursor down" },
1333
1334     /* keypad cursor keys */
1335 #ifdef KSYM_KP_Left
1336     { KSYM_KP_Left,     "XK_KP_Left",           "keypad left" },
1337     { KSYM_KP_Right,    "XK_KP_Right",          "keypad right" },
1338     { KSYM_KP_Up,       "XK_KP_Up",             "keypad up" },
1339     { KSYM_KP_Down,     "XK_KP_Down",           "keypad down" },
1340 #endif
1341
1342     /* other keypad keys */
1343 #ifdef KSYM_KP_Enter
1344     { KSYM_KP_Enter,    "XK_KP_Enter",          "keypad enter" },
1345     { KSYM_KP_Add,      "XK_KP_Add",            "keypad +" },
1346     { KSYM_KP_Subtract, "XK_KP_Subtract",       "keypad -" },
1347     { KSYM_KP_Multiply, "XK_KP_Multiply",       "keypad mltply" },
1348     { KSYM_KP_Divide,   "XK_KP_Divide",         "keypad /" },
1349     { KSYM_KP_Separator,"XK_KP_Separator",      "keypad ," },
1350 #endif
1351
1352     /* modifier keys */
1353     { KSYM_Shift_L,     "XK_Shift_L",           "left shift" },
1354     { KSYM_Shift_R,     "XK_Shift_R",           "right shift" },
1355     { KSYM_Control_L,   "XK_Control_L",         "left control" },
1356     { KSYM_Control_R,   "XK_Control_R",         "right control" },
1357     { KSYM_Meta_L,      "XK_Meta_L",            "left meta" },
1358     { KSYM_Meta_R,      "XK_Meta_R",            "right meta" },
1359     { KSYM_Alt_L,       "XK_Alt_L",             "left alt" },
1360     { KSYM_Alt_R,       "XK_Alt_R",             "right alt" },
1361 #if !defined(TARGET_SDL2)
1362     { KSYM_Super_L,     "XK_Super_L",           "left super" },  /* Win-L */
1363     { KSYM_Super_R,     "XK_Super_R",           "right super" }, /* Win-R */
1364 #endif
1365     { KSYM_Mode_switch, "XK_Mode_switch",       "mode switch" }, /* Alt-R */
1366     { KSYM_Multi_key,   "XK_Multi_key",         "multi key" },   /* Ctrl-R */
1367
1368     /* some special keys */
1369     { KSYM_BackSpace,   "XK_BackSpace",         "backspace" },
1370     { KSYM_Delete,      "XK_Delete",            "delete" },
1371     { KSYM_Insert,      "XK_Insert",            "insert" },
1372     { KSYM_Tab,         "XK_Tab",               "tab" },
1373     { KSYM_Home,        "XK_Home",              "home" },
1374     { KSYM_End,         "XK_End",               "end" },
1375     { KSYM_Page_Up,     "XK_Page_Up",           "page up" },
1376     { KSYM_Page_Down,   "XK_Page_Down",         "page down" },
1377
1378 #if defined(TARGET_SDL2)
1379     { KSYM_Menu,        "XK_Menu",              "menu" },        /* menu key */
1380     { KSYM_Back,        "XK_Back",              "back" },        /* back key */
1381 #endif
1382
1383     /* ASCII 0x20 to 0x40 keys (except numbers) */
1384     { KSYM_space,       "XK_space",             "space" },
1385     { KSYM_exclam,      "XK_exclam",            "!" },
1386     { KSYM_quotedbl,    "XK_quotedbl",          "\"" },
1387     { KSYM_numbersign,  "XK_numbersign",        "#" },
1388     { KSYM_dollar,      "XK_dollar",            "$" },
1389     { KSYM_percent,     "XK_percent",           "%" },
1390     { KSYM_ampersand,   "XK_ampersand",         "&" },
1391     { KSYM_apostrophe,  "XK_apostrophe",        "'" },
1392     { KSYM_parenleft,   "XK_parenleft",         "(" },
1393     { KSYM_parenright,  "XK_parenright",        ")" },
1394     { KSYM_asterisk,    "XK_asterisk",          "*" },
1395     { KSYM_plus,        "XK_plus",              "+" },
1396     { KSYM_comma,       "XK_comma",             "," },
1397     { KSYM_minus,       "XK_minus",             "-" },
1398     { KSYM_period,      "XK_period",            "." },
1399     { KSYM_slash,       "XK_slash",             "/" },
1400     { KSYM_colon,       "XK_colon",             ":" },
1401     { KSYM_semicolon,   "XK_semicolon",         ";" },
1402     { KSYM_less,        "XK_less",              "<" },
1403     { KSYM_equal,       "XK_equal",             "=" },
1404     { KSYM_greater,     "XK_greater",           ">" },
1405     { KSYM_question,    "XK_question",          "?" },
1406     { KSYM_at,          "XK_at",                "@" },
1407
1408     /* more ASCII keys */
1409     { KSYM_bracketleft, "XK_bracketleft",       "[" },
1410     { KSYM_backslash,   "XK_backslash",         "\\" },
1411     { KSYM_bracketright,"XK_bracketright",      "]" },
1412     { KSYM_asciicircum, "XK_asciicircum",       "^" },
1413     { KSYM_underscore,  "XK_underscore",        "_" },
1414     { KSYM_grave,       "XK_grave",             "grave" },
1415     { KSYM_quoteleft,   "XK_quoteleft",         "quote left" },
1416     { KSYM_braceleft,   "XK_braceleft",         "brace left" },
1417     { KSYM_bar,         "XK_bar",               "bar" },
1418     { KSYM_braceright,  "XK_braceright",        "brace right" },
1419     { KSYM_asciitilde,  "XK_asciitilde",        "~" },
1420
1421     /* special (non-ASCII) keys */
1422     { KSYM_degree,      "XK_degree",            "degree" },
1423     { KSYM_Adiaeresis,  "XK_Adiaeresis",        "A umlaut" },
1424     { KSYM_Odiaeresis,  "XK_Odiaeresis",        "O umlaut" },
1425     { KSYM_Udiaeresis,  "XK_Udiaeresis",        "U umlaut" },
1426     { KSYM_adiaeresis,  "XK_adiaeresis",        "a umlaut" },
1427     { KSYM_odiaeresis,  "XK_odiaeresis",        "o umlaut" },
1428     { KSYM_udiaeresis,  "XK_udiaeresis",        "u umlaut" },
1429     { KSYM_ssharp,      "XK_ssharp",            "sharp s" },
1430
1431 #if defined(TARGET_SDL2)
1432     /* special (non-ASCII) keys (UTF-8, for reverse mapping only) */
1433     { KSYM_degree,      "XK_degree",            "\xc2\xb0" },
1434     { KSYM_Adiaeresis,  "XK_Adiaeresis",        "\xc3\x84" },
1435     { KSYM_Odiaeresis,  "XK_Odiaeresis",        "\xc3\x96" },
1436     { KSYM_Udiaeresis,  "XK_Udiaeresis",        "\xc3\x9c" },
1437     { KSYM_adiaeresis,  "XK_adiaeresis",        "\xc3\xa4" },
1438     { KSYM_odiaeresis,  "XK_odiaeresis",        "\xc3\xb6" },
1439     { KSYM_udiaeresis,  "XK_udiaeresis",        "\xc3\xbc" },
1440     { KSYM_ssharp,      "XK_ssharp",            "\xc3\x9f" },
1441
1442     /* other keys (for reverse mapping only) */
1443     { KSYM_space,       "XK_space",             " " },
1444 #endif
1445
1446 #if defined(TARGET_SDL2)
1447     /* keypad keys are not in numerical order in SDL2 */
1448     { KSYM_KP_0,        "XK_KP_0",              "keypad 0" },
1449     { KSYM_KP_1,        "XK_KP_1",              "keypad 1" },
1450     { KSYM_KP_2,        "XK_KP_2",              "keypad 2" },
1451     { KSYM_KP_3,        "XK_KP_3",              "keypad 3" },
1452     { KSYM_KP_4,        "XK_KP_4",              "keypad 4" },
1453     { KSYM_KP_5,        "XK_KP_5",              "keypad 5" },
1454     { KSYM_KP_6,        "XK_KP_6",              "keypad 6" },
1455     { KSYM_KP_7,        "XK_KP_7",              "keypad 7" },
1456     { KSYM_KP_8,        "XK_KP_8",              "keypad 8" },
1457     { KSYM_KP_9,        "XK_KP_9",              "keypad 9" },
1458 #endif
1459
1460     /* end-of-array identifier */
1461     { 0,                NULL,                   NULL }
1462   };
1463
1464   int i;
1465
1466   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1467   {
1468     static char name_buffer[30];
1469     Key key = *keysym;
1470
1471     if (key >= KSYM_A && key <= KSYM_Z)
1472       sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1473     else if (key >= KSYM_a && key <= KSYM_z)
1474       sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1475     else if (key >= KSYM_0 && key <= KSYM_9)
1476       sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1477 #if !defined(TARGET_SDL2)
1478     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1479       sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1480 #endif
1481     else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1482       sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1483     else if (key == KSYM_UNDEFINED)
1484       strcpy(name_buffer, "(undefined)");
1485     else
1486     {
1487       i = 0;
1488
1489       do
1490       {
1491         if (key == translate_key[i].key)
1492         {
1493           strcpy(name_buffer, translate_key[i].name);
1494           break;
1495         }
1496       }
1497       while (translate_key[++i].name);
1498
1499       if (!translate_key[i].name)
1500         strcpy(name_buffer, "(unknown)");
1501     }
1502
1503     *name = name_buffer;
1504   }
1505   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1506   {
1507     static char name_buffer[30];
1508     Key key = *keysym;
1509
1510     if (key >= KSYM_A && key <= KSYM_Z)
1511       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1512     else if (key >= KSYM_a && key <= KSYM_z)
1513       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1514     else if (key >= KSYM_0 && key <= KSYM_9)
1515       sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1516 #if !defined(TARGET_SDL2)
1517     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1518       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1519 #endif
1520     else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1521       sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1522     else if (key == KSYM_UNDEFINED)
1523       strcpy(name_buffer, "[undefined]");
1524     else
1525     {
1526       i = 0;
1527
1528       do
1529       {
1530         if (key == translate_key[i].key)
1531         {
1532           strcpy(name_buffer, translate_key[i].x11name);
1533           break;
1534         }
1535       }
1536       while (translate_key[++i].x11name);
1537
1538       if (!translate_key[i].x11name)
1539         sprintf(name_buffer, "0x%04x", (unsigned int)key);
1540     }
1541
1542     *x11name = name_buffer;
1543   }
1544   else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1545   {
1546     Key key = KSYM_UNDEFINED;
1547     char *name_ptr = *name;
1548
1549     if (strlen(*name) == 1)
1550     {
1551       char c = name_ptr[0];
1552
1553       if (c >= 'A' && c <= 'Z')
1554         key = KSYM_A + (Key)(c - 'A');
1555       else if (c >= 'a' && c <= 'z')
1556         key = KSYM_a + (Key)(c - 'a');
1557       else if (c >= '0' && c <= '9')
1558         key = KSYM_0 + (Key)(c - '0');
1559     }
1560
1561     if (key == KSYM_UNDEFINED)
1562     {
1563       i = 0;
1564
1565       do
1566       {
1567         if (strEqual(translate_key[i].name, *name))
1568         {
1569           key = translate_key[i].key;
1570           break;
1571         }
1572       }
1573       while (translate_key[++i].x11name);
1574     }
1575
1576     if (key == KSYM_UNDEFINED)
1577       Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1578
1579     *keysym = key;
1580   }
1581   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1582   {
1583     Key key = KSYM_UNDEFINED;
1584     char *name_ptr = *x11name;
1585
1586     if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
1587     {
1588       char c = name_ptr[3];
1589
1590       if (c >= 'A' && c <= 'Z')
1591         key = KSYM_A + (Key)(c - 'A');
1592       else if (c >= 'a' && c <= 'z')
1593         key = KSYM_a + (Key)(c - 'a');
1594       else if (c >= '0' && c <= '9')
1595         key = KSYM_0 + (Key)(c - '0');
1596     }
1597 #if !defined(TARGET_SDL2)
1598     else if (strPrefix(name_ptr, "XK_KP_") && strlen(name_ptr) == 7)
1599     {
1600       char c = name_ptr[6];
1601
1602       if (c >= '0' && c <= '9')
1603         key = KSYM_KP_0 + (Key)(c - '0');
1604     }
1605 #endif
1606     else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
1607     {
1608       char c1 = name_ptr[4];
1609       char c2 = name_ptr[5];
1610       int d = 0;
1611
1612       if ((c1 >= '0' && c1 <= '9') &&
1613           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1614         d = atoi(&name_ptr[4]);
1615
1616       if (d >= 1 && d <= KSYM_NUM_FKEYS)
1617         key = KSYM_F1 + (Key)(d - 1);
1618     }
1619     else if (strPrefix(name_ptr, "XK_"))
1620     {
1621       i = 0;
1622
1623       do
1624       {
1625         if (strEqual(name_ptr, translate_key[i].x11name))
1626         {
1627           key = translate_key[i].key;
1628           break;
1629         }
1630       }
1631       while (translate_key[++i].x11name);
1632     }
1633     else if (strPrefix(name_ptr, "0x"))
1634     {
1635       unsigned int value = 0;
1636
1637       name_ptr += 2;
1638
1639       while (name_ptr)
1640       {
1641         char c = *name_ptr++;
1642         int d = -1;
1643
1644         if (c >= '0' && c <= '9')
1645           d = (int)(c - '0');
1646         else if (c >= 'a' && c <= 'f')
1647           d = (int)(c - 'a' + 10);
1648         else if (c >= 'A' && c <= 'F')
1649           d = (int)(c - 'A' + 10);
1650
1651         if (d == -1)
1652         {
1653           value = -1;
1654           break;
1655         }
1656
1657         value = value * 16 + d;
1658       }
1659
1660       if (value != -1)
1661         key = (Key)value;
1662     }
1663
1664     *keysym = key;
1665   }
1666 }
1667
1668 char *getKeyNameFromKey(Key key)
1669 {
1670   char *name;
1671
1672   translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1673   return name;
1674 }
1675
1676 char *getX11KeyNameFromKey(Key key)
1677 {
1678   char *x11name;
1679
1680   translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1681   return x11name;
1682 }
1683
1684 Key getKeyFromKeyName(char *name)
1685 {
1686   Key key;
1687
1688   translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1689   return key;
1690 }
1691
1692 Key getKeyFromX11KeyName(char *x11name)
1693 {
1694   Key key;
1695
1696   translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1697   return key;
1698 }
1699
1700 char getCharFromKey(Key key)
1701 {
1702   static struct
1703   {
1704     Key key;
1705     byte key_char;
1706   } translate_key_char[] =
1707   {
1708     /* special (non-ASCII) keys (ISO-8859-1) */
1709     { KSYM_degree,      CHAR_BYTE_DEGREE        },
1710     { KSYM_Adiaeresis,  CHAR_BYTE_UMLAUT_A      },
1711     { KSYM_Odiaeresis,  CHAR_BYTE_UMLAUT_O      },
1712     { KSYM_Udiaeresis,  CHAR_BYTE_UMLAUT_U      },
1713     { KSYM_adiaeresis,  CHAR_BYTE_UMLAUT_a      },
1714     { KSYM_odiaeresis,  CHAR_BYTE_UMLAUT_o      },
1715     { KSYM_udiaeresis,  CHAR_BYTE_UMLAUT_u      },
1716     { KSYM_ssharp,      CHAR_BYTE_SHARP_S       },
1717
1718     /* end-of-array identifier */
1719     { 0,                0                       }
1720   };
1721
1722   char *keyname = getKeyNameFromKey(key);
1723   char c = 0;
1724
1725   if (strlen(keyname) == 1)
1726     c = keyname[0];
1727   else if (strEqual(keyname, "space"))
1728     c = ' ';
1729   else
1730   {
1731     int i = 0;
1732
1733     do
1734     {
1735       if (key == translate_key_char[i].key)
1736       {
1737         c = translate_key_char[i].key_char;
1738
1739         break;
1740       }
1741     }
1742     while (translate_key_char[++i].key_char);
1743   }
1744
1745   return c;
1746 }
1747
1748 char getValidConfigValueChar(char c)
1749 {
1750   if (c == '#' ||       /* used to mark comments */
1751       c == '\\')        /* used to mark continued lines */
1752     c = 0;
1753
1754   return c;
1755 }
1756
1757
1758 /* ------------------------------------------------------------------------- */
1759 /* functions to translate string identifiers to integer or boolean value     */
1760 /* ------------------------------------------------------------------------- */
1761
1762 int get_integer_from_string(char *s)
1763 {
1764   static char *number_text[][3] =
1765   {
1766     { "0",      "zero",         "null",         },
1767     { "1",      "one",          "first"         },
1768     { "2",      "two",          "second"        },
1769     { "3",      "three",        "third"         },
1770     { "4",      "four",         "fourth"        },
1771     { "5",      "five",         "fifth"         },
1772     { "6",      "six",          "sixth"         },
1773     { "7",      "seven",        "seventh"       },
1774     { "8",      "eight",        "eighth"        },
1775     { "9",      "nine",         "ninth"         },
1776     { "10",     "ten",          "tenth"         },
1777     { "11",     "eleven",       "eleventh"      },
1778     { "12",     "twelve",       "twelfth"       },
1779
1780     { NULL,     NULL,           NULL            },
1781   };
1782
1783   int i, j;
1784   char *s_lower = getStringToLower(s);
1785   int result = -1;
1786
1787   for (i = 0; number_text[i][0] != NULL; i++)
1788     for (j = 0; j < 3; j++)
1789       if (strEqual(s_lower, number_text[i][j]))
1790         result = i;
1791
1792   if (result == -1)
1793   {
1794     if (strEqual(s_lower, "false") ||
1795         strEqual(s_lower, "no") ||
1796         strEqual(s_lower, "off"))
1797       result = 0;
1798     else if (strEqual(s_lower, "true") ||
1799              strEqual(s_lower, "yes") ||
1800              strEqual(s_lower, "on"))
1801       result = 1;
1802     else
1803       result = atoi(s);
1804   }
1805
1806   free(s_lower);
1807
1808   return result;
1809 }
1810
1811 boolean get_boolean_from_string(char *s)
1812 {
1813   char *s_lower = getStringToLower(s);
1814   boolean result = FALSE;
1815
1816   if (strEqual(s_lower, "true") ||
1817       strEqual(s_lower, "yes") ||
1818       strEqual(s_lower, "on") ||
1819       get_integer_from_string(s) == 1)
1820     result = TRUE;
1821
1822   free(s_lower);
1823
1824   return result;
1825 }
1826
1827 int get_switch3_from_string(char *s)
1828 {
1829   char *s_lower = getStringToLower(s);
1830   int result = FALSE;
1831
1832   if (strEqual(s_lower, "true") ||
1833       strEqual(s_lower, "yes") ||
1834       strEqual(s_lower, "on") ||
1835       get_integer_from_string(s) == 1)
1836     result = TRUE;
1837   else if (strEqual(s_lower, "auto"))
1838     result = AUTO;
1839
1840   free(s_lower);
1841
1842   return result;
1843 }
1844
1845
1846 /* ------------------------------------------------------------------------- */
1847 /* functions for generic lists                                               */
1848 /* ------------------------------------------------------------------------- */
1849
1850 ListNode *newListNode()
1851 {
1852   return checked_calloc(sizeof(ListNode));
1853 }
1854
1855 void addNodeToList(ListNode **node_first, char *key, void *content)
1856 {
1857   ListNode *node_new = newListNode();
1858
1859   node_new->key = getStringCopy(key);
1860   node_new->content = content;
1861   node_new->next = *node_first;
1862   *node_first = node_new;
1863 }
1864
1865 void deleteNodeFromList(ListNode **node_first, char *key,
1866                         void (*destructor_function)(void *))
1867 {
1868   if (node_first == NULL || *node_first == NULL)
1869     return;
1870
1871   if (strEqual((*node_first)->key, key))
1872   {
1873     checked_free((*node_first)->key);
1874     if (destructor_function)
1875       destructor_function((*node_first)->content);
1876     *node_first = (*node_first)->next;
1877   }
1878   else
1879     deleteNodeFromList(&(*node_first)->next, key, destructor_function);
1880 }
1881
1882 ListNode *getNodeFromKey(ListNode *node_first, char *key)
1883 {
1884   if (node_first == NULL)
1885     return NULL;
1886
1887   if (strEqual(node_first->key, key))
1888     return node_first;
1889   else
1890     return getNodeFromKey(node_first->next, key);
1891 }
1892
1893 int getNumNodes(ListNode *node_first)
1894 {
1895   return (node_first ? 1 + getNumNodes(node_first->next) : 0);
1896 }
1897
1898 void dumpList(ListNode *node_first)
1899 {
1900   ListNode *node = node_first;
1901
1902   while (node)
1903   {
1904     printf("['%s' (%d)]\n", node->key,
1905            ((struct ListNodeInfo *)node->content)->num_references);
1906     node = node->next;
1907   }
1908
1909   printf("[%d nodes]\n", getNumNodes(node_first));
1910 }
1911
1912
1913 /* ------------------------------------------------------------------------- */
1914 /* functions for file handling                                               */
1915 /* ------------------------------------------------------------------------- */
1916
1917 File *openFile(char *filename, char *mode)
1918 {
1919   File *file = checked_calloc(sizeof(File));
1920
1921   file->file = fopen(filename, mode);
1922
1923   if (file->file != NULL)
1924   {
1925     file->filename = getStringCopy(filename);
1926
1927     return file;
1928   }
1929
1930 #if defined(PLATFORM_ANDROID)
1931   file->asset_file = SDL_RWFromFile(filename, mode);
1932
1933   if (file->asset_file != NULL)
1934   {
1935     file->file_is_asset = TRUE;
1936     file->filename = getStringCopy(filename);
1937
1938     return file;
1939   }
1940 #endif
1941
1942   checked_free(file);
1943
1944   return NULL;
1945 }
1946
1947 int closeFile(File *file)
1948 {
1949   if (file == NULL)
1950     return -1;
1951
1952   int result = 0;
1953
1954 #if defined(PLATFORM_ANDROID)
1955   if (file->asset_file)
1956     result = SDL_RWclose(file->asset_file);
1957 #endif
1958
1959   if (file->file)
1960     result = fclose(file->file);
1961
1962   checked_free(file->filename);
1963   checked_free(file);
1964
1965   return result;
1966 }
1967
1968 int checkEndOfFile(File *file)
1969 {
1970 #if defined(PLATFORM_ANDROID)
1971   if (file->file_is_asset)
1972     return file->end_of_file;
1973 #endif
1974
1975   return feof(file->file);
1976 }
1977
1978 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
1979 {
1980 #if defined(PLATFORM_ANDROID)
1981   if (file->file_is_asset)
1982   {
1983     if (file->end_of_file)
1984       return 0;
1985
1986     size_t num_items_read =
1987       SDL_RWread(file->asset_file, buffer, item_size, num_items);
1988
1989     if (num_items_read < num_items)
1990       file->end_of_file = TRUE;
1991
1992     return num_items_read;
1993   }
1994 #endif
1995
1996   return fread(buffer, item_size, num_items, file->file);
1997 }
1998
1999 int seekFile(File *file, long offset, int whence)
2000 {
2001 #if defined(PLATFORM_ANDROID)
2002   if (file->file_is_asset)
2003   {
2004     int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
2005                       whence == SEEK_CUR ? RW_SEEK_CUR :
2006                       whence == SEEK_END ? RW_SEEK_END : 0);
2007
2008     return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
2009   }
2010 #endif
2011
2012   return fseek(file->file, offset, whence);
2013 }
2014
2015 int getByteFromFile(File *file)
2016 {
2017 #if defined(PLATFORM_ANDROID)
2018   if (file->file_is_asset)
2019   {
2020     if (file->end_of_file)
2021       return EOF;
2022
2023     byte c;
2024     size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
2025
2026     if (num_bytes_read < 1)
2027       file->end_of_file = TRUE;
2028
2029     return (file->end_of_file ? EOF : (int)c);
2030   }
2031 #endif
2032
2033   return fgetc(file->file);
2034 }
2035
2036 char *getStringFromFile(File *file, char *line, int size)
2037 {
2038 #if defined(PLATFORM_ANDROID)
2039   if (file->file_is_asset)
2040   {
2041     if (file->end_of_file)
2042       return NULL;
2043
2044     char *line_ptr = line;
2045     int num_bytes_read = 0;
2046
2047     while (num_bytes_read < size - 1 &&
2048            SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
2049            *line_ptr++ != '\n')
2050       num_bytes_read++;
2051
2052     *line_ptr = '\0';
2053
2054     if (strlen(line) == 0)
2055     {
2056       file->end_of_file = TRUE;
2057
2058       return NULL;
2059     }
2060
2061     return line;
2062   }
2063 #endif
2064
2065   return fgets(line, size, file->file);
2066 }
2067
2068
2069 /* ------------------------------------------------------------------------- */
2070 /* functions for directory handling                                          */
2071 /* ------------------------------------------------------------------------- */
2072
2073 Directory *openDirectory(char *dir_name)
2074 {
2075   Directory *dir = checked_calloc(sizeof(Directory));
2076
2077   dir->dir = opendir(dir_name);
2078
2079   if (dir->dir != NULL)
2080   {
2081     dir->filename = getStringCopy(dir_name);
2082
2083     return dir;
2084   }
2085
2086 #if defined(PLATFORM_ANDROID)
2087   char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
2088
2089   dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
2090
2091   checked_free(asset_toc_filename);
2092
2093   if (dir->asset_toc_file != NULL)
2094   {
2095     dir->directory_is_asset = TRUE;
2096     dir->filename = getStringCopy(dir_name);
2097
2098     return dir;
2099   }
2100 #endif
2101
2102   checked_free(dir);
2103
2104   return NULL;
2105 }
2106
2107 int closeDirectory(Directory *dir)
2108 {
2109   if (dir == NULL)
2110     return -1;
2111
2112   int result = 0;
2113
2114 #if defined(PLATFORM_ANDROID)
2115   if (dir->asset_toc_file)
2116     result = SDL_RWclose(dir->asset_toc_file);
2117 #endif
2118
2119   if (dir->dir)
2120     result = closedir(dir->dir);
2121
2122   if (dir->dir_entry)
2123     freeDirectoryEntry(dir->dir_entry);
2124
2125   checked_free(dir->filename);
2126   checked_free(dir);
2127
2128   return result;
2129 }
2130
2131 DirectoryEntry *readDirectory(Directory *dir)
2132 {
2133   if (dir->dir_entry)
2134     freeDirectoryEntry(dir->dir_entry);
2135
2136   dir->dir_entry = NULL;
2137
2138 #if defined(PLATFORM_ANDROID)
2139   if (dir->directory_is_asset)
2140   {
2141     char line[MAX_LINE_LEN];
2142     char *line_ptr = line;
2143     int num_bytes_read = 0;
2144
2145     while (num_bytes_read < MAX_LINE_LEN - 1 &&
2146            SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
2147            *line_ptr != '\n')
2148     {
2149       line_ptr++;
2150       num_bytes_read++;
2151     }
2152
2153     *line_ptr = '\0';
2154
2155     if (strlen(line) == 0)
2156       return NULL;
2157
2158     dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2159
2160     dir->dir_entry->is_directory = FALSE;
2161     if (line[strlen(line) - 1] == '/')
2162     {
2163       dir->dir_entry->is_directory = TRUE;
2164
2165       line[strlen(line) - 1] = '\0';
2166     }
2167
2168     dir->dir_entry->basename = getStringCopy(line);
2169     dir->dir_entry->filename = getPath2(dir->filename, line);
2170
2171     return dir->dir_entry;
2172   }
2173 #endif
2174
2175   struct dirent *dir_entry = readdir(dir->dir);
2176
2177   if (dir_entry == NULL)
2178     return NULL;
2179
2180   dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
2181
2182   dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
2183   dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
2184
2185   struct stat file_status;
2186
2187   dir->dir_entry->is_directory =
2188     (stat(dir->dir_entry->filename, &file_status) == 0 &&
2189      (file_status.st_mode & S_IFMT) == S_IFDIR);
2190
2191   return dir->dir_entry;
2192 }
2193
2194 void freeDirectoryEntry(DirectoryEntry *dir_entry)
2195 {
2196   if (dir_entry == NULL)
2197     return;
2198
2199   checked_free(dir_entry->basename);
2200   checked_free(dir_entry->filename);
2201   checked_free(dir_entry);
2202 }
2203
2204
2205 /* ------------------------------------------------------------------------- */
2206 /* functions for checking files and filenames                                */
2207 /* ------------------------------------------------------------------------- */
2208
2209 boolean directoryExists(char *dir_name)
2210 {
2211   if (dir_name == NULL)
2212     return FALSE;
2213
2214   boolean success = (access(dir_name, F_OK) == 0);
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 *basename)
2303 {
2304   return (!strEqual(basename, ".") &&
2305           !strEqual(basename, "..") &&
2306           !fileHasSuffix(basename, "txt") &&
2307           !fileHasSuffix(basename, "conf"));
2308 }
2309
2310 boolean FileIsGraphic(char *filename)
2311 {
2312   char *basename = getBaseNamePtr(filename);
2313
2314   return FileCouldBeArtwork(basename);
2315 }
2316
2317 boolean FileIsSound(char *filename)
2318 {
2319   char *basename = getBaseNamePtr(filename);
2320
2321   return FileCouldBeArtwork(basename);
2322 }
2323
2324 boolean FileIsMusic(char *filename)
2325 {
2326   char *basename = getBaseNamePtr(filename);
2327
2328   return FileCouldBeArtwork(basename);
2329 }
2330
2331 boolean FileIsArtworkType(char *basename, int type)
2332 {
2333   if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(basename)) ||
2334       (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(basename)) ||
2335       (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(basename)))
2336     return TRUE;
2337
2338   return FALSE;
2339 }
2340
2341 /* ------------------------------------------------------------------------- */
2342 /* functions for loading artwork configuration information                   */
2343 /* ------------------------------------------------------------------------- */
2344
2345 char *get_mapped_token(char *token)
2346 {
2347   /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
2348   static char *map_token_prefix[][2] =
2349   {
2350     { "char_procent",           "char_percent"  },
2351     { NULL,                                     }
2352   };
2353   int i;
2354
2355   for (i = 0; map_token_prefix[i][0] != NULL; i++)
2356   {
2357     int len_token_prefix = strlen(map_token_prefix[i][0]);
2358
2359     if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
2360       return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
2361   }
2362
2363   return NULL;
2364 }
2365
2366 /* This function checks if a string <s> of the format "string1, string2, ..."
2367    exactly contains a string <s_contained>. */
2368
2369 static boolean string_has_parameter(char *s, char *s_contained)
2370 {
2371   char *substring;
2372
2373   if (s == NULL || s_contained == NULL)
2374     return FALSE;
2375
2376   if (strlen(s_contained) > strlen(s))
2377     return FALSE;
2378
2379   if (strncmp(s, s_contained, strlen(s_contained)) == 0)
2380   {
2381     char next_char = s[strlen(s_contained)];
2382
2383     /* check if next character is delimiter or whitespace */
2384     return (next_char == ',' || next_char == '\0' ||
2385             next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
2386   }
2387
2388   /* check if string contains another parameter string after a comma */
2389   substring = strchr(s, ',');
2390   if (substring == NULL)        /* string does not contain a comma */
2391     return FALSE;
2392
2393   /* advance string pointer to next character after the comma */
2394   substring++;
2395
2396   /* skip potential whitespaces after the comma */
2397   while (*substring == ' ' || *substring == '\t')
2398     substring++;
2399
2400   return string_has_parameter(substring, s_contained);
2401 }
2402
2403 int get_parameter_value(char *value_raw, char *suffix, int type)
2404 {
2405   char *value = getStringToLower(value_raw);
2406   int result = 0;       /* probably a save default value */
2407
2408   if (strEqual(suffix, ".direction"))
2409   {
2410     result = (strEqual(value, "left")  ? MV_LEFT :
2411               strEqual(value, "right") ? MV_RIGHT :
2412               strEqual(value, "up")    ? MV_UP :
2413               strEqual(value, "down")  ? MV_DOWN : MV_NONE);
2414   }
2415   else if (strEqual(suffix, ".align"))
2416   {
2417     result = (strEqual(value, "left")   ? ALIGN_LEFT :
2418               strEqual(value, "right")  ? ALIGN_RIGHT :
2419               strEqual(value, "center") ? ALIGN_CENTER :
2420               strEqual(value, "middle") ? ALIGN_CENTER : ALIGN_DEFAULT);
2421   }
2422   else if (strEqual(suffix, ".valign"))
2423   {
2424     result = (strEqual(value, "top")    ? VALIGN_TOP :
2425               strEqual(value, "bottom") ? VALIGN_BOTTOM :
2426               strEqual(value, "middle") ? VALIGN_MIDDLE :
2427               strEqual(value, "center") ? VALIGN_MIDDLE : VALIGN_DEFAULT);
2428   }
2429   else if (strEqual(suffix, ".anim_mode"))
2430   {
2431     result = (string_has_parameter(value, "none")       ? ANIM_NONE :
2432               string_has_parameter(value, "loop")       ? ANIM_LOOP :
2433               string_has_parameter(value, "linear")     ? ANIM_LINEAR :
2434               string_has_parameter(value, "pingpong")   ? ANIM_PINGPONG :
2435               string_has_parameter(value, "pingpong2")  ? ANIM_PINGPONG2 :
2436               string_has_parameter(value, "random")     ? ANIM_RANDOM :
2437               string_has_parameter(value, "ce_value")   ? ANIM_CE_VALUE :
2438               string_has_parameter(value, "ce_score")   ? ANIM_CE_SCORE :
2439               string_has_parameter(value, "ce_delay")   ? ANIM_CE_DELAY :
2440               string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
2441               string_has_parameter(value, "vertical")   ? ANIM_VERTICAL :
2442               string_has_parameter(value, "centered")   ? ANIM_CENTERED :
2443               ANIM_DEFAULT);
2444
2445     if (string_has_parameter(value, "reverse"))
2446       result |= ANIM_REVERSE;
2447
2448     if (string_has_parameter(value, "opaque_player"))
2449       result |= ANIM_OPAQUE_PLAYER;
2450
2451     if (string_has_parameter(value, "static_panel"))
2452       result |= ANIM_STATIC_PANEL;
2453   }
2454   else if (strEqual(suffix, ".class"))
2455   {
2456     result = get_hash_from_key(value);
2457   }
2458   else if (strEqual(suffix, ".style"))
2459   {
2460     result = STYLE_DEFAULT;
2461
2462     if (string_has_parameter(value, "accurate_borders"))
2463       result |= STYLE_ACCURATE_BORDERS;
2464
2465     if (string_has_parameter(value, "inner_corners"))
2466       result |= STYLE_INNER_CORNERS;
2467   }
2468   else if (strEqual(suffix, ".fade_mode"))
2469   {
2470     result = (string_has_parameter(value, "none")       ? FADE_MODE_NONE :
2471               string_has_parameter(value, "fade")       ? FADE_MODE_FADE :
2472               string_has_parameter(value, "crossfade")  ? FADE_MODE_CROSSFADE :
2473               string_has_parameter(value, "melt")       ? FADE_MODE_MELT :
2474               FADE_MODE_DEFAULT);
2475   }
2476   else if (strPrefix(suffix, ".font"))          /* (may also be ".font_xyz") */
2477   {
2478     result = gfx.get_font_from_token_function(value);
2479   }
2480   else          /* generic parameter of type integer or boolean */
2481   {
2482     result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
2483               type == TYPE_INTEGER ? get_integer_from_string(value) :
2484               type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
2485               ARG_UNDEFINED_VALUE);
2486   }
2487
2488   free(value);
2489
2490   return result;
2491 }
2492
2493 struct ScreenModeInfo *get_screen_mode_from_string(char *screen_mode_string)
2494 {
2495   static struct ScreenModeInfo screen_mode;
2496   char *screen_mode_string_x = strchr(screen_mode_string, 'x');
2497   char *screen_mode_string_copy;
2498   char *screen_mode_string_pos_w;
2499   char *screen_mode_string_pos_h;
2500
2501   if (screen_mode_string_x == NULL)     /* invalid screen mode format */
2502     return NULL;
2503
2504   screen_mode_string_copy = getStringCopy(screen_mode_string);
2505
2506   screen_mode_string_pos_w = screen_mode_string_copy;
2507   screen_mode_string_pos_h = strchr(screen_mode_string_copy, 'x');
2508   *screen_mode_string_pos_h++ = '\0';
2509
2510   screen_mode.width  = atoi(screen_mode_string_pos_w);
2511   screen_mode.height = atoi(screen_mode_string_pos_h);
2512
2513   return &screen_mode;
2514 }
2515
2516 void get_aspect_ratio_from_screen_mode(struct ScreenModeInfo *screen_mode,
2517                                        int *x, int *y)
2518 {
2519   float aspect_ratio = (float)screen_mode->width / (float)screen_mode->height;
2520   float aspect_ratio_new;
2521   int i = 1;
2522
2523   do
2524   {
2525     *x = i * aspect_ratio + 0.000001;
2526     *y = i;
2527
2528     aspect_ratio_new = (float)*x / (float)*y;
2529
2530     i++;
2531   }
2532   while (aspect_ratio_new != aspect_ratio && *y < screen_mode->height);
2533 }
2534
2535 static void FreeCustomArtworkList(struct ArtworkListInfo *,
2536                                   struct ListNodeInfo ***, int *);
2537
2538 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2539                                            struct ConfigTypeInfo *suffix_list,
2540                                            char **ignore_tokens,
2541                                            int num_file_list_entries)
2542 {
2543   struct FileInfo *file_list;
2544   int num_file_list_entries_found = 0;
2545   int num_suffix_list_entries = 0;
2546   int list_pos;
2547   int i, j;
2548
2549   file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2550
2551   for (i = 0; suffix_list[i].token != NULL; i++)
2552     num_suffix_list_entries++;
2553
2554   /* always start with reliable default values */
2555   for (i = 0; i < num_file_list_entries; i++)
2556   {
2557     file_list[i].token = NULL;
2558
2559     file_list[i].default_filename = NULL;
2560     file_list[i].filename = NULL;
2561
2562     if (num_suffix_list_entries > 0)
2563     {
2564       int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2565
2566       file_list[i].default_parameter = checked_calloc(parameter_array_size);
2567       file_list[i].parameter = checked_calloc(parameter_array_size);
2568
2569       for (j = 0; j < num_suffix_list_entries; j++)
2570       {
2571         setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2572         setString(&file_list[i].parameter[j], suffix_list[j].value);
2573       }
2574
2575       file_list[i].redefined = FALSE;
2576       file_list[i].fallback_to_default = FALSE;
2577       file_list[i].default_is_cloned = FALSE;
2578     }
2579   }
2580
2581   list_pos = 0;
2582
2583   for (i = 0; config_list[i].token != NULL; i++)
2584   {
2585     int len_config_token = strlen(config_list[i].token);
2586     boolean is_file_entry = TRUE;
2587
2588     for (j = 0; suffix_list[j].token != NULL; j++)
2589     {
2590       int len_suffix = strlen(suffix_list[j].token);
2591
2592       if (len_suffix < len_config_token &&
2593           strEqual(&config_list[i].token[len_config_token - len_suffix],
2594                    suffix_list[j].token))
2595       {
2596         setString(&file_list[list_pos].default_parameter[j],
2597                   config_list[i].value);
2598
2599         is_file_entry = FALSE;
2600
2601         break;
2602       }
2603     }
2604
2605     /* the following tokens are no file definitions, but other config tokens */
2606     for (j = 0; ignore_tokens[j] != NULL; j++)
2607       if (strEqual(config_list[i].token, ignore_tokens[j]))
2608         is_file_entry = FALSE;
2609
2610     if (is_file_entry)
2611     {
2612       if (i > 0)
2613         list_pos++;
2614
2615       if (list_pos >= num_file_list_entries)
2616         break;
2617
2618       file_list[list_pos].token = config_list[i].token;
2619       file_list[list_pos].default_filename = config_list[i].value;
2620     }
2621
2622     if (strSuffix(config_list[i].token, ".clone_from"))
2623       file_list[list_pos].default_is_cloned = TRUE;
2624   }
2625
2626   num_file_list_entries_found = list_pos + 1;
2627   if (num_file_list_entries_found != num_file_list_entries)
2628   {
2629     Error(ERR_INFO_LINE, "-");
2630     Error(ERR_INFO, "inconsistant config list information:");
2631     Error(ERR_INFO, "- should be:   %d (according to 'src/conf_xxx.h')",
2632           num_file_list_entries);
2633     Error(ERR_INFO, "- found to be: %d (according to 'src/conf_xxx.c')",
2634           num_file_list_entries_found);
2635     Error(ERR_EXIT,   "please fix");
2636   }
2637
2638   return file_list;
2639 }
2640
2641 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
2642 {
2643   int len_token = strlen(token);
2644   int len_suffix = strlen(suffix);
2645
2646   if (start_pos < 0)    /* compare suffix from end of string */
2647     start_pos += len_token;
2648
2649   if (start_pos < 0 || start_pos + len_suffix > len_token)
2650     return FALSE;
2651
2652   if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
2653     return FALSE;
2654
2655   if (token[start_pos + len_suffix] == '\0')
2656     return TRUE;
2657
2658   if (token[start_pos + len_suffix] == '.')
2659     return TRUE;
2660
2661   return FALSE;
2662 }
2663
2664 #define KNOWN_TOKEN_VALUE       "[KNOWN_TOKEN_VALUE]"
2665
2666 static void read_token_parameters(SetupFileHash *setup_file_hash,
2667                                   struct ConfigTypeInfo *suffix_list,
2668                                   struct FileInfo *file_list_entry)
2669 {
2670   /* check for config token that is the base token without any suffixes */
2671   char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
2672   char *known_token_value = KNOWN_TOKEN_VALUE;
2673   int i;
2674
2675   if (filename != NULL)
2676   {
2677     setString(&file_list_entry->filename, filename);
2678
2679     /* when file definition found, set all parameters to default values */
2680     for (i = 0; suffix_list[i].token != NULL; i++)
2681       setString(&file_list_entry->parameter[i], suffix_list[i].value);
2682
2683     file_list_entry->redefined = TRUE;
2684
2685     /* mark config file token as well known from default config */
2686     setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
2687   }
2688
2689   /* check for config tokens that can be build by base token and suffixes */
2690   for (i = 0; suffix_list[i].token != NULL; i++)
2691   {
2692     char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
2693     char *value = getHashEntry(setup_file_hash, token);
2694
2695     if (value != NULL)
2696     {
2697       setString(&file_list_entry->parameter[i], value);
2698
2699       /* mark config file token as well known from default config */
2700       setHashEntry(setup_file_hash, token, known_token_value);
2701     }
2702
2703     free(token);
2704   }
2705 }
2706
2707 static void add_dynamic_file_list_entry(struct FileInfo **list,
2708                                         int *num_list_entries,
2709                                         SetupFileHash *extra_file_hash,
2710                                         struct ConfigTypeInfo *suffix_list,
2711                                         int num_suffix_list_entries,
2712                                         char *token)
2713 {
2714   struct FileInfo *new_list_entry;
2715   int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2716
2717   (*num_list_entries)++;
2718   *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
2719   new_list_entry = &(*list)[*num_list_entries - 1];
2720
2721   new_list_entry->token = getStringCopy(token);
2722   new_list_entry->default_filename = NULL;
2723   new_list_entry->filename = NULL;
2724   new_list_entry->parameter = checked_calloc(parameter_array_size);
2725
2726   new_list_entry->redefined = FALSE;
2727   new_list_entry->fallback_to_default = FALSE;
2728   new_list_entry->default_is_cloned = FALSE;
2729
2730   read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
2731 }
2732
2733 static void add_property_mapping(struct PropertyMapping **list,
2734                                  int *num_list_entries,
2735                                  int base_index, int ext1_index,
2736                                  int ext2_index, int ext3_index,
2737                                  int artwork_index)
2738 {
2739   struct PropertyMapping *new_list_entry;
2740
2741   (*num_list_entries)++;
2742   *list = checked_realloc(*list,
2743                           *num_list_entries * sizeof(struct PropertyMapping));
2744   new_list_entry = &(*list)[*num_list_entries - 1];
2745
2746   new_list_entry->base_index = base_index;
2747   new_list_entry->ext1_index = ext1_index;
2748   new_list_entry->ext2_index = ext2_index;
2749   new_list_entry->ext3_index = ext3_index;
2750
2751   new_list_entry->artwork_index = artwork_index;
2752 }
2753
2754 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
2755                                           char *filename)
2756 {
2757   struct FileInfo *file_list = artwork_info->file_list;
2758   struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2759   char **base_prefixes = artwork_info->base_prefixes;
2760   char **ext1_suffixes = artwork_info->ext1_suffixes;
2761   char **ext2_suffixes = artwork_info->ext2_suffixes;
2762   char **ext3_suffixes = artwork_info->ext3_suffixes;
2763   char **ignore_tokens = artwork_info->ignore_tokens;
2764   int num_file_list_entries = artwork_info->num_file_list_entries;
2765   int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
2766   int num_base_prefixes = artwork_info->num_base_prefixes;
2767   int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
2768   int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
2769   int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
2770   int num_ignore_tokens = artwork_info->num_ignore_tokens;
2771   SetupFileHash *setup_file_hash, *valid_file_hash;
2772   SetupFileHash *extra_file_hash, *empty_file_hash;
2773   char *known_token_value = KNOWN_TOKEN_VALUE;
2774   int i, j, k, l;
2775
2776   if (filename == NULL)
2777     return;
2778
2779   if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
2780     return;
2781
2782   /* separate valid (defined) from empty (undefined) config token values */
2783   valid_file_hash = newSetupFileHash();
2784   empty_file_hash = newSetupFileHash();
2785   BEGIN_HASH_ITERATION(setup_file_hash, itr)
2786   {
2787     char *value = HASH_ITERATION_VALUE(itr);
2788
2789     setHashEntry(*value ? valid_file_hash : empty_file_hash,
2790                  HASH_ITERATION_TOKEN(itr), value);
2791   }
2792   END_HASH_ITERATION(setup_file_hash, itr)
2793
2794   /* at this point, we do not need the setup file hash anymore -- free it */
2795   freeSetupFileHash(setup_file_hash);
2796
2797   /* map deprecated to current tokens (using prefix match and replace) */
2798   BEGIN_HASH_ITERATION(valid_file_hash, itr)
2799   {
2800     char *token = HASH_ITERATION_TOKEN(itr);
2801     char *mapped_token = get_mapped_token(token);
2802
2803     if (mapped_token != NULL)
2804     {
2805       char *value = HASH_ITERATION_VALUE(itr);
2806
2807       /* add mapped token */
2808       setHashEntry(valid_file_hash, mapped_token, value);
2809
2810       /* ignore old token (by setting it to "known" keyword) */
2811       setHashEntry(valid_file_hash, token, known_token_value);
2812
2813       free(mapped_token);
2814     }
2815   }
2816   END_HASH_ITERATION(valid_file_hash, itr)
2817
2818   /* read parameters for all known config file tokens */
2819   for (i = 0; i < num_file_list_entries; i++)
2820     read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
2821
2822   /* set all tokens that can be ignored here to "known" keyword */
2823   for (i = 0; i < num_ignore_tokens; i++)
2824     setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
2825
2826   /* copy all unknown config file tokens to extra config hash */
2827   extra_file_hash = newSetupFileHash();
2828   BEGIN_HASH_ITERATION(valid_file_hash, itr)
2829   {
2830     char *value = HASH_ITERATION_VALUE(itr);
2831
2832     if (!strEqual(value, known_token_value))
2833       setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
2834   }
2835   END_HASH_ITERATION(valid_file_hash, itr)
2836
2837   /* at this point, we do not need the valid file hash anymore -- free it */
2838   freeSetupFileHash(valid_file_hash);
2839
2840   /* now try to determine valid, dynamically defined config tokens */
2841
2842   BEGIN_HASH_ITERATION(extra_file_hash, itr)
2843   {
2844     struct FileInfo **dynamic_file_list =
2845       &artwork_info->dynamic_file_list;
2846     int *num_dynamic_file_list_entries =
2847       &artwork_info->num_dynamic_file_list_entries;
2848     struct PropertyMapping **property_mapping =
2849       &artwork_info->property_mapping;
2850     int *num_property_mapping_entries =
2851       &artwork_info->num_property_mapping_entries;
2852     int current_summarized_file_list_entry =
2853       artwork_info->num_file_list_entries +
2854       artwork_info->num_dynamic_file_list_entries;
2855     char *token = HASH_ITERATION_TOKEN(itr);
2856     int len_token = strlen(token);
2857     int start_pos;
2858     boolean base_prefix_found = FALSE;
2859     boolean parameter_suffix_found = FALSE;
2860
2861     /* skip all parameter definitions (handled by read_token_parameters()) */
2862     for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
2863     {
2864       int len_suffix = strlen(suffix_list[i].token);
2865
2866       if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
2867         parameter_suffix_found = TRUE;
2868     }
2869
2870     if (parameter_suffix_found)
2871       continue;
2872
2873     /* ---------- step 0: search for matching base prefix ---------- */
2874
2875     start_pos = 0;
2876     for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
2877     {
2878       char *base_prefix = base_prefixes[i];
2879       int len_base_prefix = strlen(base_prefix);
2880       boolean ext1_suffix_found = FALSE;
2881       boolean ext2_suffix_found = FALSE;
2882       boolean ext3_suffix_found = FALSE;
2883       boolean exact_match = FALSE;
2884       int base_index = -1;
2885       int ext1_index = -1;
2886       int ext2_index = -1;
2887       int ext3_index = -1;
2888
2889       base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
2890
2891       if (!base_prefix_found)
2892         continue;
2893
2894       base_index = i;
2895
2896       if (start_pos + len_base_prefix == len_token)     /* exact match */
2897       {
2898         exact_match = TRUE;
2899
2900         add_dynamic_file_list_entry(dynamic_file_list,
2901                                     num_dynamic_file_list_entries,
2902                                     extra_file_hash,
2903                                     suffix_list,
2904                                     num_suffix_list_entries,
2905                                     token);
2906         add_property_mapping(property_mapping,
2907                              num_property_mapping_entries,
2908                              base_index, -1, -1, -1,
2909                              current_summarized_file_list_entry);
2910         continue;
2911       }
2912
2913       /* ---------- step 1: search for matching first suffix ---------- */
2914
2915       start_pos += len_base_prefix;
2916       for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
2917       {
2918         char *ext1_suffix = ext1_suffixes[j];
2919         int len_ext1_suffix = strlen(ext1_suffix);
2920
2921         ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
2922
2923         if (!ext1_suffix_found)
2924           continue;
2925
2926         ext1_index = j;
2927
2928         if (start_pos + len_ext1_suffix == len_token)   /* exact match */
2929         {
2930           exact_match = TRUE;
2931
2932           add_dynamic_file_list_entry(dynamic_file_list,
2933                                       num_dynamic_file_list_entries,
2934                                       extra_file_hash,
2935                                       suffix_list,
2936                                       num_suffix_list_entries,
2937                                       token);
2938           add_property_mapping(property_mapping,
2939                                num_property_mapping_entries,
2940                                base_index, ext1_index, -1, -1,
2941                                current_summarized_file_list_entry);
2942           continue;
2943         }
2944
2945         start_pos += len_ext1_suffix;
2946       }
2947
2948       if (exact_match)
2949         break;
2950
2951       /* ---------- step 2: search for matching second suffix ---------- */
2952
2953       for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
2954       {
2955         char *ext2_suffix = ext2_suffixes[k];
2956         int len_ext2_suffix = strlen(ext2_suffix);
2957
2958         ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
2959
2960         if (!ext2_suffix_found)
2961           continue;
2962
2963         ext2_index = k;
2964
2965         if (start_pos + len_ext2_suffix == len_token)   /* exact match */
2966         {
2967           exact_match = TRUE;
2968
2969           add_dynamic_file_list_entry(dynamic_file_list,
2970                                       num_dynamic_file_list_entries,
2971                                       extra_file_hash,
2972                                       suffix_list,
2973                                       num_suffix_list_entries,
2974                                       token);
2975           add_property_mapping(property_mapping,
2976                                num_property_mapping_entries,
2977                                base_index, ext1_index, ext2_index, -1,
2978                                current_summarized_file_list_entry);
2979           continue;
2980         }
2981
2982         start_pos += len_ext2_suffix;
2983       }
2984
2985       if (exact_match)
2986         break;
2987
2988       /* ---------- step 3: search for matching third suffix ---------- */
2989
2990       for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
2991       {
2992         char *ext3_suffix = ext3_suffixes[l];
2993         int len_ext3_suffix = strlen(ext3_suffix);
2994
2995         ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
2996
2997         if (!ext3_suffix_found)
2998           continue;
2999
3000         ext3_index = l;
3001
3002         if (start_pos + len_ext3_suffix == len_token) /* exact match */
3003         {
3004           exact_match = TRUE;
3005
3006           add_dynamic_file_list_entry(dynamic_file_list,
3007                                       num_dynamic_file_list_entries,
3008                                       extra_file_hash,
3009                                       suffix_list,
3010                                       num_suffix_list_entries,
3011                                       token);
3012           add_property_mapping(property_mapping,
3013                                num_property_mapping_entries,
3014                                base_index, ext1_index, ext2_index, ext3_index,
3015                                current_summarized_file_list_entry);
3016           continue;
3017         }
3018       }
3019     }
3020   }
3021   END_HASH_ITERATION(extra_file_hash, itr)
3022
3023   if (artwork_info->num_dynamic_file_list_entries > 0)
3024   {
3025     artwork_info->dynamic_artwork_list =
3026       checked_calloc(artwork_info->num_dynamic_file_list_entries *
3027                      artwork_info->sizeof_artwork_list_entry);
3028   }
3029
3030   if (options.verbose && IS_PARENT_PROCESS())
3031   {
3032     SetupFileList *setup_file_list, *list;
3033     boolean dynamic_tokens_found = FALSE;
3034     boolean unknown_tokens_found = FALSE;
3035     boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
3036
3037     if ((setup_file_list = loadSetupFileList(filename)) == NULL)
3038       Error(ERR_EXIT, "loadSetupFileHash works, but loadSetupFileList fails");
3039
3040     BEGIN_HASH_ITERATION(extra_file_hash, itr)
3041     {
3042       if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
3043         dynamic_tokens_found = TRUE;
3044       else
3045         unknown_tokens_found = TRUE;
3046     }
3047     END_HASH_ITERATION(extra_file_hash, itr)
3048
3049     if (options.debug && dynamic_tokens_found)
3050     {
3051       Error(ERR_INFO_LINE, "-");
3052       Error(ERR_INFO, "dynamic token(s) found in config file:");
3053       Error(ERR_INFO, "- config file: '%s'", filename);
3054
3055       for (list = setup_file_list; list != NULL; list = list->next)
3056       {
3057         char *value = getHashEntry(extra_file_hash, list->token);
3058
3059         if (value != NULL && strEqual(value, known_token_value))
3060           Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3061       }
3062
3063       Error(ERR_INFO_LINE, "-");
3064     }
3065
3066     if (unknown_tokens_found)
3067     {
3068       Error(ERR_INFO_LINE, "-");
3069       Error(ERR_INFO, "warning: unknown token(s) found in config file:");
3070       Error(ERR_INFO, "- config file: '%s'", filename);
3071
3072       for (list = setup_file_list; list != NULL; list = list->next)
3073       {
3074         char *value = getHashEntry(extra_file_hash, list->token);
3075
3076         if (value != NULL && !strEqual(value, known_token_value))
3077           Error(ERR_INFO, "- dynamic token: '%s'", list->token);
3078       }
3079
3080       Error(ERR_INFO_LINE, "-");
3081     }
3082
3083     if (undefined_values_found)
3084     {
3085       Error(ERR_INFO_LINE, "-");
3086       Error(ERR_INFO, "warning: undefined values found in config file:");
3087       Error(ERR_INFO, "- config file: '%s'", filename);
3088
3089       for (list = setup_file_list; list != NULL; list = list->next)
3090       {
3091         char *value = getHashEntry(empty_file_hash, list->token);
3092
3093         if (value != NULL)
3094           Error(ERR_INFO, "- undefined value for token: '%s'", list->token);
3095       }
3096
3097       Error(ERR_INFO_LINE, "-");
3098     }
3099
3100     freeSetupFileList(setup_file_list);
3101   }
3102
3103   freeSetupFileHash(extra_file_hash);
3104   freeSetupFileHash(empty_file_hash);
3105 }
3106
3107 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
3108 {
3109   struct FileInfo *file_list = artwork_info->file_list;
3110   int num_file_list_entries = artwork_info->num_file_list_entries;
3111   int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3112   char *filename_base = UNDEFINED_FILENAME, *filename_local;
3113   int i, j;
3114
3115   DrawInitText("Loading artwork config", 120, FC_GREEN);
3116   DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
3117
3118   /* always start with reliable default values */
3119   for (i = 0; i < num_file_list_entries; i++)
3120   {
3121     setString(&file_list[i].filename, file_list[i].default_filename);
3122
3123     for (j = 0; j < num_suffix_list_entries; j++)
3124       setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
3125
3126     file_list[i].redefined = FALSE;
3127     file_list[i].fallback_to_default = FALSE;
3128   }
3129
3130   /* free previous dynamic artwork file array */
3131   if (artwork_info->dynamic_file_list != NULL)
3132   {
3133     for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
3134     {
3135       free(artwork_info->dynamic_file_list[i].token);
3136       free(artwork_info->dynamic_file_list[i].filename);
3137       free(artwork_info->dynamic_file_list[i].parameter);
3138     }
3139
3140     free(artwork_info->dynamic_file_list);
3141     artwork_info->dynamic_file_list = NULL;
3142
3143     FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3144                           &artwork_info->num_dynamic_file_list_entries);
3145   }
3146
3147   /* free previous property mapping */
3148   if (artwork_info->property_mapping != NULL)
3149   {
3150     free(artwork_info->property_mapping);
3151
3152     artwork_info->property_mapping = NULL;
3153     artwork_info->num_property_mapping_entries = 0;
3154   }
3155
3156   if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
3157   {
3158     /* first look for special artwork configured in level series config */
3159     filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
3160
3161     if (fileExists(filename_base))
3162       LoadArtworkConfigFromFilename(artwork_info, filename_base);
3163   }
3164
3165   filename_local = getCustomArtworkConfigFilename(artwork_info->type);
3166
3167   if (filename_local != NULL && !strEqual(filename_base, filename_local))
3168     LoadArtworkConfigFromFilename(artwork_info, filename_local);
3169 }
3170
3171 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
3172                                    struct ListNodeInfo **listnode)
3173 {
3174   if (*listnode)
3175   {
3176     char *filename = (*listnode)->source_filename;
3177
3178     if (--(*listnode)->num_references <= 0)
3179       deleteNodeFromList(&artwork_info->content_list, filename,
3180                          artwork_info->free_artwork);
3181
3182     *listnode = NULL;
3183   }
3184 }
3185
3186 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
3187                                     struct ListNodeInfo **listnode,
3188                                     struct FileInfo *file_list_entry)
3189 {
3190   char *init_text[] =
3191   {
3192     "Loading graphics",
3193     "Loading sounds",
3194     "Loading music"
3195   };
3196
3197   ListNode *node;
3198   char *basename = file_list_entry->filename;
3199   char *filename = getCustomArtworkFilename(basename, artwork_info->type);
3200
3201   if (filename == NULL)
3202   {
3203     Error(ERR_WARN, "cannot find artwork file '%s'", basename);
3204
3205     basename = file_list_entry->default_filename;
3206
3207     /* fail for cloned default artwork that has no default filename defined */
3208     if (file_list_entry->default_is_cloned &&
3209         strEqual(basename, UNDEFINED_FILENAME))
3210     {
3211       int error_mode = ERR_WARN;
3212
3213       /* we can get away without sounds and music, but not without graphics */
3214       if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3215         error_mode = ERR_EXIT;
3216
3217       Error(error_mode, "token '%s' was cloned and has no default filename",
3218             file_list_entry->token);
3219
3220       return;
3221     }
3222
3223     /* dynamic artwork has no default filename / skip empty default artwork */
3224     if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
3225       return;
3226
3227     file_list_entry->fallback_to_default = TRUE;
3228
3229     Error(ERR_WARN, "trying default artwork file '%s'", basename);
3230
3231     filename = getCustomArtworkFilename(basename, artwork_info->type);
3232
3233     if (filename == NULL)
3234     {
3235       int error_mode = ERR_WARN;
3236
3237       /* we can get away without sounds and music, but not without graphics */
3238       if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3239         error_mode = ERR_EXIT;
3240
3241       Error(error_mode, "cannot find default artwork file '%s'", basename);
3242
3243       return;
3244     }
3245   }
3246
3247   /* check if the old and the new artwork file are the same */
3248   if (*listnode && strEqual((*listnode)->source_filename, filename))
3249   {
3250     /* The old and new artwork are the same (have the same filename and path).
3251        This usually means that this artwork does not exist in this artwork set
3252        and a fallback to the existing artwork is done. */
3253
3254     return;
3255   }
3256
3257   /* delete existing artwork file entry */
3258   deleteArtworkListEntry(artwork_info, listnode);
3259
3260   /* check if the new artwork file already exists in the list of artwork */
3261   if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
3262   {
3263       *listnode = (struct ListNodeInfo *)node->content;
3264       (*listnode)->num_references++;
3265
3266       return;
3267   }
3268
3269   DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
3270   DrawInitText(basename, 150, FC_YELLOW);
3271
3272   if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
3273   {
3274     /* add new artwork file entry to the list of artwork files */
3275     (*listnode)->num_references = 1;
3276     addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
3277                   *listnode);
3278   }
3279   else
3280   {
3281     int error_mode = ERR_WARN;
3282
3283     /* we can get away without sounds and music, but not without graphics */
3284     if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
3285       error_mode = ERR_EXIT;
3286
3287     Error(error_mode, "cannot load artwork file '%s'", basename);
3288
3289     return;
3290   }
3291 }
3292
3293 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
3294                               struct ListNodeInfo **listnode,
3295                               struct FileInfo *file_list_entry)
3296 {
3297   if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
3298   {
3299     deleteArtworkListEntry(artwork_info, listnode);
3300
3301     return;
3302   }
3303
3304   replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
3305 }
3306
3307 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
3308 {
3309   struct FileInfo *file_list = artwork_info->file_list;
3310   struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
3311   int num_file_list_entries = artwork_info->num_file_list_entries;
3312   int num_dynamic_file_list_entries =
3313     artwork_info->num_dynamic_file_list_entries;
3314   int i;
3315
3316   print_timestamp_init("ReloadCustomArtworkList");
3317
3318   for (i = 0; i < num_file_list_entries; i++)
3319     LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
3320                       &file_list[i]);
3321
3322   for (i = 0; i < num_dynamic_file_list_entries; i++)
3323     LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
3324                       &dynamic_file_list[i]);
3325
3326   print_timestamp_done("ReloadCustomArtworkList");
3327
3328 #if 0
3329   dumpList(artwork_info->content_list);
3330 #endif
3331 }
3332
3333 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
3334                                   struct ListNodeInfo ***list,
3335                                   int *num_list_entries)
3336 {
3337   int i;
3338
3339   if (*list == NULL)
3340     return;
3341
3342   for (i = 0; i < *num_list_entries; i++)
3343     deleteArtworkListEntry(artwork_info, &(*list)[i]);
3344   free(*list);
3345
3346   *list = NULL;
3347   *num_list_entries = 0;
3348 }
3349
3350 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
3351 {
3352   if (artwork_info == NULL)
3353     return;
3354
3355   FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
3356                         &artwork_info->num_file_list_entries);
3357
3358   FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
3359                         &artwork_info->num_dynamic_file_list_entries);
3360 }
3361
3362
3363 /* ------------------------------------------------------------------------- */
3364 /* functions only needed for non-Unix (non-command-line) systems             */
3365 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt")    */
3366 /* (now also added for Windows, to create files in user data directory)      */
3367 /* ------------------------------------------------------------------------- */
3368
3369 char *getErrorFilename(char *basename)
3370 {
3371   return getPath2(getUserGameDataDir(), basename);
3372 }
3373
3374 void openErrorFile()
3375 {
3376   InitUserDataDirectory();
3377
3378   if ((program.error_file = fopen(program.error_filename, MODE_WRITE)) == NULL)
3379   {
3380     program.error_file = stderr;
3381
3382     Error(ERR_WARN, "cannot open file '%s' for writing: %s",
3383           program.error_filename, strerror(errno));
3384   }
3385
3386   /* error output should be unbuffered so it is not truncated in a crash */
3387   setbuf(program.error_file, NULL);
3388 }
3389
3390 void closeErrorFile()
3391 {
3392   if (program.error_file != stderr)     /* do not close stream 'stderr' */
3393     fclose(program.error_file);
3394 }
3395
3396 void dumpErrorFile()
3397 {
3398   FILE *error_file = fopen(program.error_filename, MODE_READ);
3399
3400   if (error_file != NULL)
3401   {
3402     while (!feof(error_file))
3403       fputc(fgetc(error_file), stderr);
3404
3405     fclose(error_file);
3406   }
3407 }
3408
3409 void NotifyUserAboutErrorFile()
3410 {
3411 #if defined(PLATFORM_WIN32)
3412   char *title_text = getStringCat2(program.program_title, " Error Message");
3413   char *error_text = getStringCat2("The program was aborted due to an error; "
3414                                    "for details, see the following error file:"
3415                                    STRING_NEWLINE, program.error_filename);
3416
3417   MessageBox(NULL, error_text, title_text, MB_OK);
3418 #endif
3419 }
3420
3421
3422 /* ------------------------------------------------------------------------- */
3423 /* the following is only for debugging purpose and normally not used         */
3424 /* ------------------------------------------------------------------------- */
3425
3426 #if DEBUG
3427
3428 #define DEBUG_PRINT_INIT_TIMESTAMPS             FALSE
3429 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH       10
3430
3431 #define DEBUG_NUM_TIMESTAMPS                    10
3432 #define DEBUG_TIME_IN_MICROSECONDS              0
3433
3434 #if DEBUG_TIME_IN_MICROSECONDS
3435 static double Counter_Microseconds()
3436 {
3437   static struct timeval base_time = { 0, 0 };
3438   struct timeval current_time;
3439   double counter;
3440
3441   gettimeofday(&current_time, NULL);
3442
3443   /* reset base time in case of wrap-around */
3444   if (current_time.tv_sec < base_time.tv_sec)
3445     base_time = current_time;
3446
3447   counter =
3448     ((double)(current_time.tv_sec  - base_time.tv_sec)) * 1000000 +
3449     ((double)(current_time.tv_usec - base_time.tv_usec));
3450
3451   return counter;               /* return microseconds since last init */
3452 }
3453 #endif
3454
3455 char *debug_print_timestamp_get_padding(int padding_size)
3456 {
3457   static char *padding = NULL;
3458   int max_padding_size = 100;
3459
3460   if (padding == NULL)
3461   {
3462     padding = checked_calloc(max_padding_size + 1);
3463     memset(padding, ' ', max_padding_size);
3464   }
3465
3466   return &padding[MAX(0, max_padding_size - padding_size)];
3467 }
3468
3469 void debug_print_timestamp(int counter_nr, char *message)
3470 {
3471   int indent_size = 8;
3472   int padding_size = 40;
3473   float timestamp_interval;
3474
3475   if (counter_nr < 0)
3476     Error(ERR_EXIT, "debugging: invalid negative counter");
3477   else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
3478     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
3479
3480 #if DEBUG_TIME_IN_MICROSECONDS
3481   static double counter[DEBUG_NUM_TIMESTAMPS][2];
3482   char *unit = "ms";
3483
3484   counter[counter_nr][0] = Counter_Microseconds();
3485 #else
3486   static int counter[DEBUG_NUM_TIMESTAMPS][2];
3487   char *unit = "s";
3488
3489   counter[counter_nr][0] = Counter();
3490 #endif
3491
3492   timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
3493   counter[counter_nr][1] = counter[counter_nr][0];
3494
3495   if (message)
3496     Error(ERR_DEBUG, "%s%s%s %.3f %s",
3497            debug_print_timestamp_get_padding(counter_nr * indent_size),
3498            message,
3499            debug_print_timestamp_get_padding(padding_size - strlen(message)),
3500            timestamp_interval / 1000,
3501            unit);
3502 }
3503
3504 void debug_print_parent_only(char *format, ...)
3505 {
3506   if (!IS_PARENT_PROCESS())
3507     return;
3508
3509   if (format)
3510   {
3511     va_list ap;
3512
3513     va_start(ap, format);
3514     vprintf(format, ap);
3515     va_end(ap);
3516
3517     printf("\n");
3518   }
3519 }
3520
3521 #endif  /* DEBUG */
3522
3523 void print_timestamp_ext(char *message, char *mode)
3524 {
3525 #if DEBUG_PRINT_INIT_TIMESTAMPS
3526   static char *debug_message = NULL;
3527   static char *last_message = NULL;
3528   static int counter_nr = 0;
3529   int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
3530
3531   checked_free(debug_message);
3532   debug_message = getStringCat3(mode, " ", message);
3533
3534   if (strEqual(mode, "INIT"))
3535   {
3536     debug_print_timestamp(counter_nr, NULL);
3537
3538     if (counter_nr + 1 < max_depth)
3539       debug_print_timestamp(counter_nr, debug_message);
3540
3541     counter_nr++;
3542
3543     debug_print_timestamp(counter_nr, NULL);
3544   }
3545   else if (strEqual(mode, "DONE"))
3546   {
3547     counter_nr--;
3548
3549     if (counter_nr + 1 < max_depth ||
3550         (counter_nr == 0 && max_depth == 1))
3551     {
3552       last_message = message;
3553
3554       if (counter_nr == 0 && max_depth == 1)
3555       {
3556         checked_free(debug_message);
3557         debug_message = getStringCat3("TIME", " ", message);
3558       }
3559
3560       debug_print_timestamp(counter_nr, debug_message);
3561     }
3562   }
3563   else if (!strEqual(mode, "TIME") ||
3564            !strEqual(message, last_message))
3565   {
3566     if (counter_nr < max_depth)
3567       debug_print_timestamp(counter_nr, debug_message);
3568   }
3569 #endif
3570 }
3571
3572 void print_timestamp_init(char *message)
3573 {
3574   print_timestamp_ext(message, "INIT");
3575 }
3576
3577 void print_timestamp_time(char *message)
3578 {
3579   print_timestamp_ext(message, "TIME");
3580 }
3581
3582 void print_timestamp_done(char *message)
3583 {
3584   print_timestamp_ext(message, "DONE");
3585 }