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