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