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