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