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