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