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