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