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