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