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