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