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