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