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