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