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