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