rnd-20060727-1-src
[rocksndiamonds.git] / src / libgame / misc.c
1 /***********************************************************
2 * Artsoft Retro-Game Library                               *
3 *----------------------------------------------------------*
4 * (c) 1994-2002 Artsoft Entertainment                      *
5 *               Holger Schemel                             *
6 *               Detmolder Strasse 189                      *
7 *               33604 Bielefeld                            *
8 *               Germany                                    *
9 *               e-mail: info@artsoft.org                   *
10 *----------------------------------------------------------*
11 * misc.c                                                   *
12 ***********************************************************/
13
14 #include <time.h>
15 #include <sys/time.h>
16 #include <sys/types.h>
17 #include <stdarg.h>
18 #include <ctype.h>
19 #include <string.h>
20 #include <unistd.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 /* platform independent wrappers for printf() et al. (newline aware)         */
42 /* ------------------------------------------------------------------------- */
43
44 static void vfprintf_newline(FILE *stream, char *format, va_list ap)
45 {
46   char *newline = STRING_NEWLINE;
47
48   vfprintf(stream, format, ap);
49
50   fprintf(stream, "%s", newline);
51 }
52
53 static void vprintf_error_ext(char *format, va_list ap, boolean print_newline)
54 {
55   FILE *error_file = openErrorFile();   /* this returns at least 'stderr' */
56
57   if (print_newline)
58     vfprintf_newline(error_file, format, ap);
59   else
60     vfprintf(error_file, format, ap);
61
62   if (error_file != stderr)             /* do not close stream 'stderr' */
63     fclose(error_file);
64 }
65
66 static void vprintf_error(char *format, va_list ap)
67 {
68   vprintf_error_ext(format, ap, FALSE);
69 }
70
71 static void vprintf_error_newline(char *format, va_list ap)
72 {
73   vprintf_error_ext(format, ap, TRUE);
74 }
75
76 static void printf_error(char *format, ...)
77 {
78   if (format)
79   {
80     va_list ap;
81
82     va_start(ap, format);
83     vprintf_error(format, ap);
84     va_end(ap);
85   }
86 }
87
88 static void printf_error_newline(char *format, ...)
89 {
90   if (format)
91   {
92     va_list ap;
93
94     va_start(ap, format);
95     vprintf_error_newline(format, ap);
96     va_end(ap);
97   }
98 }
99
100 static void fprintf_newline(FILE *stream, char *format, ...)
101 {
102   if (format)
103   {
104     va_list ap;
105
106     va_start(ap, format);
107     vfprintf_newline(stream, format, ap);
108     va_end(ap);
109   }
110 }
111
112 static char *get_line_string(char *line_chars, int line_length)
113 {
114   static char *buffer = NULL;
115   int line_chars_length = strlen(line_chars);
116   int i;
117
118   if (buffer != NULL)
119     checked_free(buffer);
120
121   buffer = checked_malloc(line_chars_length * line_length + 1);
122
123   for (i = 0; i < line_length; i++)
124     strcpy(&buffer[i * line_chars_length], line_chars);
125
126   return buffer;
127 }
128
129 void fprintf_line(FILE *stream, char *line_chars, int line_length)
130 {
131   fprintf_newline(stream, get_line_string(line_chars, line_length));
132 }
133
134 void printf_line(char *line_chars, int line_length)
135 {
136   fprintf_line(stdout, line_chars, line_length);
137 }
138
139 void printf_line_error(char *line_chars, int line_length)
140 {
141   printf_error_newline(get_line_string(line_chars, line_length));
142 }
143
144 void printf_line_with_prefix(char *prefix, char *line_chars, int line_length)
145 {
146   fprintf(stdout, "%s", prefix);
147   fprintf_line(stdout, line_chars, line_length);
148 }
149
150
151 /* ------------------------------------------------------------------------- */
152 /* string functions                                                          */
153 /* ------------------------------------------------------------------------- */
154
155 /* int2str() returns a number converted to a string;
156    the used memory is static, but will be overwritten by later calls,
157    so if you want to save the result, copy it to a private string buffer;
158    there can be 10 local calls of int2str() without buffering the result --
159    the 11th call will then destroy the result from the first call and so on.
160 */
161
162 char *int2str(int number, int size)
163 {
164   static char shift_array[10][40];
165   static int shift_counter = 0;
166   char *s = shift_array[shift_counter];
167
168   shift_counter = (shift_counter + 1) % 10;
169
170   if (size > 20)
171     size = 20;
172
173   if (size)
174   {
175     sprintf(s, "                    %09d", number);
176     return &s[strlen(s) - size];
177   }
178   else
179   {
180     sprintf(s, "%d", number);
181     return s;
182   }
183 }
184
185
186 /* something similar to "int2str()" above, but allocates its own memory
187    and has a different interface; we cannot use "itoa()", because this
188    seems to be already defined when cross-compiling to the win32 target */
189
190 char *i_to_a(unsigned int i)
191 {
192   static char *a = NULL;
193
194   checked_free(a);
195
196   if (i > 2147483647)   /* yes, this is a kludge */
197     i = 2147483647;
198
199   a = checked_malloc(10 + 1);
200
201   sprintf(a, "%d", i);
202
203   return a;
204 }
205
206
207 /* calculate base-2 logarithm of argument (rounded down to integer;
208    this function returns the number of the highest bit set in argument) */
209
210 int log_2(unsigned int x)
211 {
212   int e = 0;
213
214   while ((1 << e) < x)
215   {
216     x -= (1 << e);      /* for rounding down (rounding up: remove this line) */
217     e++;
218   }
219
220   return e;
221 }
222
223
224 /* ------------------------------------------------------------------------- */
225 /* counter functions                                                         */
226 /* ------------------------------------------------------------------------- */
227
228 #if defined(PLATFORM_MSDOS)
229 volatile unsigned long counter = 0;
230
231 void increment_counter()
232 {
233   counter++;
234 }
235
236 END_OF_FUNCTION(increment_counter);
237 #endif
238
239
240 /* maximal allowed length of a command line option */
241 #define MAX_OPTION_LEN          256
242
243 #ifdef TARGET_SDL
244 static unsigned long mainCounter(int mode)
245 {
246   static unsigned long base_ms = 0;
247   unsigned long current_ms;
248   unsigned long counter_ms;
249
250   current_ms = SDL_GetTicks();
251
252   /* reset base time in case of counter initializing or wrap-around */
253   if (mode == INIT_COUNTER || current_ms < base_ms)
254     base_ms = current_ms;
255
256   counter_ms = current_ms - base_ms;
257
258   return counter_ms;            /* return milliseconds since last init */
259 }
260
261 #else /* !TARGET_SDL */
262
263 #if defined(PLATFORM_UNIX)
264 static unsigned long mainCounter(int mode)
265 {
266   static struct timeval base_time = { 0, 0 };
267   struct timeval current_time;
268   unsigned long counter_ms;
269
270   gettimeofday(&current_time, NULL);
271
272   /* reset base time in case of counter initializing or wrap-around */
273   if (mode == INIT_COUNTER || current_time.tv_sec < base_time.tv_sec)
274     base_time = current_time;
275
276   counter_ms = (current_time.tv_sec  - base_time.tv_sec)  * 1000
277              + (current_time.tv_usec - base_time.tv_usec) / 1000;
278
279   return counter_ms;            /* return milliseconds since last init */
280 }
281 #endif /* PLATFORM_UNIX */
282 #endif /* !TARGET_SDL */
283
284 void InitCounter()              /* set counter back to zero */
285 {
286 #if !defined(PLATFORM_MSDOS)
287   mainCounter(INIT_COUNTER);
288 #else
289   LOCK_VARIABLE(counter);
290   LOCK_FUNCTION(increment_counter);
291   install_int_ex(increment_counter, BPS_TO_TIMER(100));
292 #endif
293 }
294
295 unsigned long Counter() /* get milliseconds since last call of InitCounter() */
296 {
297 #if !defined(PLATFORM_MSDOS)
298   return mainCounter(READ_COUNTER);
299 #else
300   return (counter * 10);
301 #endif
302 }
303
304 static void sleep_milliseconds(unsigned long milliseconds_delay)
305 {
306   boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
307
308   if (do_busy_waiting)
309   {
310     /* we want to wait only a few ms -- if we assume that we have a
311        kernel timer resolution of 10 ms, we would wait far to long;
312        therefore it's better to do a short interval of busy waiting
313        to get our sleeping time more accurate */
314
315     unsigned long base_counter = Counter(), actual_counter = Counter();
316
317     while (actual_counter < base_counter + milliseconds_delay &&
318            actual_counter >= base_counter)
319       actual_counter = Counter();
320   }
321   else
322   {
323 #if defined(TARGET_SDL)
324     SDL_Delay(milliseconds_delay);
325 #elif defined(TARGET_ALLEGRO)
326     rest(milliseconds_delay);
327 #else
328     struct timeval delay;
329
330     delay.tv_sec  = milliseconds_delay / 1000;
331     delay.tv_usec = 1000 * (milliseconds_delay % 1000);
332
333     if (select(0, NULL, NULL, NULL, &delay) != 0)
334       Error(ERR_WARN, "sleep_milliseconds(): select() failed");
335 #endif
336   }
337 }
338
339 void Delay(unsigned long delay) /* Sleep specified number of milliseconds */
340 {
341   sleep_milliseconds(delay);
342 }
343
344 boolean FrameReached(unsigned long *frame_counter_var,
345                      unsigned long frame_delay)
346 {
347   unsigned long actual_frame_counter = FrameCounter;
348
349   if (actual_frame_counter >= *frame_counter_var &&
350       actual_frame_counter < *frame_counter_var + frame_delay)
351     return FALSE;
352
353   *frame_counter_var = actual_frame_counter;
354
355   return TRUE;
356 }
357
358 boolean DelayReached(unsigned long *counter_var,
359                      unsigned long delay)
360 {
361   unsigned long actual_counter = Counter();
362
363   if (actual_counter >= *counter_var &&
364       actual_counter < *counter_var + delay)
365     return FALSE;
366
367   *counter_var = actual_counter;
368
369   return TRUE;
370 }
371
372 void WaitUntilDelayReached(unsigned long *counter_var, unsigned long delay)
373 {
374   unsigned long actual_counter;
375
376   while (1)
377   {
378     actual_counter = Counter();
379
380     if (actual_counter >= *counter_var &&
381         actual_counter < *counter_var + delay)
382       sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
383     else
384       break;
385   }
386
387   *counter_var = actual_counter;
388 }
389
390
391 /* ------------------------------------------------------------------------- */
392 /* random generator functions                                                */
393 /* ------------------------------------------------------------------------- */
394
395 unsigned int init_random_number(int nr, long seed)
396 {
397   if (seed == NEW_RANDOMIZE)
398   {
399 #if defined(TARGET_SDL)
400     seed = (long)SDL_GetTicks();
401 #else
402     struct timeval current_time;
403
404     gettimeofday(&current_time, NULL);
405     seed = (long)current_time.tv_usec;
406 #endif
407   }
408
409   srandom_linux_libc(nr, (unsigned int) seed);
410
411   return (unsigned int) seed;
412 }
413
414 unsigned int get_random_number(int nr, int max)
415 {
416   return (max > 0 ? random_linux_libc(nr) % max : 0);
417 }
418
419
420 /* ------------------------------------------------------------------------- */
421 /* system info functions                                                     */
422 /* ------------------------------------------------------------------------- */
423
424 #if !defined(PLATFORM_MSDOS)
425 static char *get_corrected_real_name(char *real_name)
426 {
427   char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
428   char *from_ptr = real_name;
429   char *to_ptr   = real_name_new;
430
431   /* copy the name string, but not more than MAX_USERNAME_LEN characters */
432   while (*from_ptr && (long)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
433   {
434     /* the name field read from "passwd" file may also contain additional
435        user information, separated by commas, which will be removed here */
436     if (*from_ptr == ',')
437       break;
438
439     /* the user's real name may contain 'ß' characters (german sharp s),
440        which have no equivalent in upper case letters (used by our fonts) */
441     if (*from_ptr == 'ß')
442     {
443       from_ptr++;
444       *to_ptr++ = 's';
445       *to_ptr++ = 's';
446     }
447     else
448       *to_ptr++ = *from_ptr++;
449   }
450
451   *to_ptr = '\0';
452
453   return real_name_new;
454 }
455 #endif
456
457 char *getLoginName()
458 {
459   static char *login_name = NULL;
460
461 #if defined(PLATFORM_WIN32)
462   if (login_name == NULL)
463   {
464     unsigned long buffer_size = MAX_USERNAME_LEN + 1;
465     login_name = checked_malloc(buffer_size);
466
467     if (GetUserName(login_name, &buffer_size) == 0)
468       strcpy(login_name, ANONYMOUS_NAME);
469   }
470 #else
471   if (login_name == NULL)
472   {
473     struct passwd *pwd;
474
475     if ((pwd = getpwuid(getuid())) == NULL)
476       login_name = ANONYMOUS_NAME;
477     else
478       login_name = getStringCopy(pwd->pw_name);
479   }
480 #endif
481
482   return login_name;
483 }
484
485 char *getRealName()
486 {
487   static char *real_name = NULL;
488
489 #if defined(PLATFORM_WIN32)
490   if (real_name == NULL)
491   {
492     static char buffer[MAX_USERNAME_LEN + 1];
493     unsigned long buffer_size = MAX_USERNAME_LEN + 1;
494
495     if (GetUserName(buffer, &buffer_size) != 0)
496       real_name = get_corrected_real_name(buffer);
497     else
498       real_name = ANONYMOUS_NAME;
499   }
500 #elif defined(PLATFORM_UNIX)
501   if (real_name == NULL)
502   {
503     struct passwd *pwd;
504
505     if ((pwd = getpwuid(getuid())) != NULL && strlen(pwd->pw_gecos) != 0)
506       real_name = get_corrected_real_name(pwd->pw_gecos);
507     else
508       real_name = ANONYMOUS_NAME;
509   }
510 #else
511   real_name = ANONYMOUS_NAME;
512 #endif
513
514   return real_name;
515 }
516
517 char *getHomeDir()
518 {
519   static char *dir = NULL;
520
521 #if defined(PLATFORM_WIN32)
522   if (dir == NULL)
523   {
524     dir = checked_malloc(MAX_PATH + 1);
525
526     if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, 0, dir)))
527       strcpy(dir, ".");
528   }
529 #elif defined(PLATFORM_UNIX)
530   if (dir == NULL)
531   {
532     if ((dir = getenv("HOME")) == NULL)
533     {
534       struct passwd *pwd;
535
536       if ((pwd = getpwuid(getuid())) != NULL)
537         dir = getStringCopy(pwd->pw_dir);
538       else
539         dir = ".";
540     }
541   }
542 #else
543   dir = ".";
544 #endif
545
546   return dir;
547 }
548
549
550 /* ------------------------------------------------------------------------- */
551 /* path manipulation functions                                               */
552 /* ------------------------------------------------------------------------- */
553
554 static char *getLastPathSeparatorPtr(char *filename)
555 {
556   char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
557
558   if (last_separator == NULL)   /* also try DOS/Windows variant */
559     last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
560
561   return last_separator;
562 }
563
564 char *getBaseNamePtr(char *filename)
565 {
566   char *last_separator = getLastPathSeparatorPtr(filename);
567
568   if (last_separator != NULL)
569     return last_separator + 1;  /* separator found: strip base path */
570   else
571     return filename;            /* no separator found: filename has no path */
572 }
573
574 char *getBaseName(char *filename)
575 {
576   return getStringCopy(getBaseNamePtr(filename));
577 }
578
579 char *getBasePath(char *filename)
580 {
581   char *basepath = getStringCopy(filename);
582   char *last_separator = getLastPathSeparatorPtr(basepath);
583
584   if (last_separator != NULL)
585     *last_separator = '\0';     /* separator found: strip basename */
586   else
587     basepath = ".";             /* no separator found: use current path */
588
589   return basepath;
590 }
591
592
593 /* ------------------------------------------------------------------------- */
594 /* various string functions                                                  */
595 /* ------------------------------------------------------------------------- */
596
597 char *getPath2(char *path1, char *path2)
598 {
599   char *sep = STRING_PATH_SEPARATOR;
600   char *complete_path = checked_malloc(strlen(path1) + 1 +
601                                        strlen(path2) + 1);
602
603   sprintf(complete_path, "%s%s%s", path1, sep, path2);
604
605   return complete_path;
606 }
607
608 char *getPath3(char *path1, char *path2, char *path3)
609 {
610   char *sep = STRING_PATH_SEPARATOR;
611   char *complete_path = checked_malloc(strlen(path1) + 1 +
612                                        strlen(path2) + 1 +
613                                        strlen(path3) + 1);
614
615   sprintf(complete_path, "%s%s%s%s%s", path1, sep, path2, sep, path3);
616
617   return complete_path;
618 }
619
620 char *getStringCat2(char *s1, char *s2)
621 {
622   char *complete_string = checked_malloc(strlen(s1) + strlen(s2) + 1);
623
624   sprintf(complete_string, "%s%s", s1, s2);
625
626   return complete_string;
627 }
628
629 char *getStringCopy(char *s)
630 {
631   char *s_copy;
632
633   if (s == NULL)
634     return NULL;
635
636   s_copy = checked_malloc(strlen(s) + 1);
637   strcpy(s_copy, s);
638
639   return s_copy;
640 }
641
642 char *getStringToLower(char *s)
643 {
644   char *s_copy = checked_malloc(strlen(s) + 1);
645   char *s_ptr = s_copy;
646
647   while (*s)
648     *s_ptr++ = tolower(*s++);
649   *s_ptr = '\0';
650
651   return s_copy;
652 }
653
654 void setString(char **old_value, char *new_value)
655 {
656   checked_free(*old_value);
657
658   *old_value = getStringCopy(new_value);
659 }
660
661 boolean strEqual(char *s1, char *s2)
662 {
663   return (s1 == NULL && s2 == NULL ? TRUE  :
664           s1 == NULL && s2 != NULL ? FALSE :
665           s1 != NULL && s2 == NULL ? FALSE :
666           strcmp(s1, s2) == 0);
667 }
668
669
670 /* ------------------------------------------------------------------------- */
671 /* command line option handling functions                                    */
672 /* ------------------------------------------------------------------------- */
673
674 void GetOptions(char *argv[], void (*print_usage_function)(void))
675 {
676   char *ro_base_path = RO_BASE_PATH;
677   char *rw_base_path = RW_BASE_PATH;
678   char **options_left = &argv[1];
679
680 #if !defined(PLATFORM_MACOSX)
681   /* if the program is configured to start from current directory (default),
682      determine program package directory (KDE/Konqueror does not do this by
683      itself and fails otherwise); on Mac OS X, the program binary is stored
684      in an application package directory -- do not try to use this directory
685      as the program data directory (Mac OS X handles this correctly anyway) */
686
687   if (strEqual(ro_base_path, "."))
688     ro_base_path = program.command_basepath;
689   if (strEqual(rw_base_path, "."))
690     rw_base_path = program.command_basepath;
691 #endif
692
693   /* initialize global program options */
694   options.display_name = NULL;
695   options.server_host = NULL;
696   options.server_port = 0;
697   options.ro_base_directory = ro_base_path;
698   options.rw_base_directory = rw_base_path;
699   options.level_directory    = getPath2(ro_base_path, LEVELS_DIRECTORY);
700   options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
701   options.sounds_directory   = getPath2(ro_base_path, SOUNDS_DIRECTORY);
702   options.music_directory    = getPath2(ro_base_path, MUSIC_DIRECTORY);
703   options.docs_directory     = getPath2(ro_base_path, DOCS_DIRECTORY);
704   options.execute_command = NULL;
705   options.serveronly = FALSE;
706   options.network = FALSE;
707   options.verbose = FALSE;
708   options.debug = FALSE;
709
710 #if !defined(PLATFORM_UNIX)
711   if (*options_left == NULL)    /* no options given -- enable verbose mode */
712     options.verbose = TRUE;
713 #endif
714
715   while (*options_left)
716   {
717     char option_str[MAX_OPTION_LEN];
718     char *option = options_left[0];
719     char *next_option = options_left[1];
720     char *option_arg = NULL;
721     int option_len = strlen(option);
722
723     if (option_len >= MAX_OPTION_LEN)
724       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
725
726     strcpy(option_str, option);                 /* copy argument into buffer */
727     option = option_str;
728
729     if (strEqual(option, "--"))                 /* stop scanning arguments */
730       break;
731
732     if (strncmp(option, "--", 2) == 0)          /* treat '--' like '-' */
733       option++;
734
735     option_arg = strchr(option, '=');
736     if (option_arg == NULL)                     /* no '=' in option */
737       option_arg = next_option;
738     else
739     {
740       *option_arg++ = '\0';                     /* cut argument from option */
741       if (*option_arg == '\0')                  /* no argument after '=' */
742         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
743     }
744
745     option_len = strlen(option);
746
747     if (strEqual(option, "-"))
748       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
749     else if (strncmp(option, "-help", option_len) == 0)
750     {
751       print_usage_function();
752
753       exit(0);
754     }
755     else if (strncmp(option, "-display", option_len) == 0)
756     {
757       if (option_arg == NULL)
758         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
759
760       options.display_name = option_arg;
761       if (option_arg == next_option)
762         options_left++;
763     }
764     else if (strncmp(option, "-basepath", option_len) == 0)
765     {
766       if (option_arg == NULL)
767         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
768
769       /* this should be extended to separate options for ro and rw data */
770       options.ro_base_directory = ro_base_path = option_arg;
771       options.rw_base_directory = rw_base_path = option_arg;
772       if (option_arg == next_option)
773         options_left++;
774
775       /* adjust paths for sub-directories in base directory accordingly */
776       options.level_directory    = getPath2(ro_base_path, LEVELS_DIRECTORY);
777       options.graphics_directory = getPath2(ro_base_path, GRAPHICS_DIRECTORY);
778       options.sounds_directory   = getPath2(ro_base_path, SOUNDS_DIRECTORY);
779       options.music_directory    = getPath2(ro_base_path, MUSIC_DIRECTORY);
780       options.docs_directory     = getPath2(ro_base_path, DOCS_DIRECTORY);
781     }
782     else if (strncmp(option, "-levels", option_len) == 0)
783     {
784       if (option_arg == NULL)
785         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
786
787       options.level_directory = option_arg;
788       if (option_arg == next_option)
789         options_left++;
790     }
791     else if (strncmp(option, "-graphics", option_len) == 0)
792     {
793       if (option_arg == NULL)
794         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
795
796       options.graphics_directory = option_arg;
797       if (option_arg == next_option)
798         options_left++;
799     }
800     else if (strncmp(option, "-sounds", option_len) == 0)
801     {
802       if (option_arg == NULL)
803         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
804
805       options.sounds_directory = option_arg;
806       if (option_arg == next_option)
807         options_left++;
808     }
809     else if (strncmp(option, "-music", option_len) == 0)
810     {
811       if (option_arg == NULL)
812         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
813
814       options.music_directory = option_arg;
815       if (option_arg == next_option)
816         options_left++;
817     }
818     else if (strncmp(option, "-network", option_len) == 0)
819     {
820       options.network = TRUE;
821     }
822     else if (strncmp(option, "-serveronly", option_len) == 0)
823     {
824       options.serveronly = TRUE;
825     }
826     else if (strncmp(option, "-verbose", option_len) == 0)
827     {
828       options.verbose = TRUE;
829     }
830     else if (strncmp(option, "-debug", option_len) == 0)
831     {
832       options.debug = TRUE;
833     }
834     else if (strncmp(option, "-execute", option_len) == 0)
835     {
836       if (option_arg == NULL)
837         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
838
839       options.execute_command = option_arg;
840       if (option_arg == next_option)
841         options_left++;
842
843       /* when doing batch processing, always enable verbose mode (warnings) */
844       options.verbose = TRUE;
845     }
846     else if (*option == '-')
847     {
848       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
849     }
850     else if (options.server_host == NULL)
851     {
852       options.server_host = *options_left;
853     }
854     else if (options.server_port == 0)
855     {
856       options.server_port = atoi(*options_left);
857       if (options.server_port < 1024)
858         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
859     }
860     else
861       Error(ERR_EXIT_HELP, "too many arguments");
862
863     options_left++;
864   }
865 }
866
867
868 /* ------------------------------------------------------------------------- */
869 /* error handling functions                                                  */
870 /* ------------------------------------------------------------------------- */
871
872 /* used by SetError() and GetError() to store internal error messages */
873 static char internal_error[1024];       /* this is bad */
874
875 void SetError(char *format, ...)
876 {
877   va_list ap;
878
879   va_start(ap, format);
880   vsprintf(internal_error, format, ap);
881   va_end(ap);
882 }
883
884 char *GetError()
885 {
886   return internal_error;
887 }
888
889 #if 1
890
891 void Error(int mode, char *format, ...)
892 {
893   static boolean last_line_was_separator = FALSE;
894   char *process_name = "";
895
896   /* display warnings only when running in verbose mode */
897   if (mode & ERR_WARN && !options.verbose)
898     return;
899
900   if (mode == ERR_RETURN_LINE)
901   {
902     if (!last_line_was_separator)
903       printf_line_error(format, 79);
904
905     last_line_was_separator = TRUE;
906
907     return;
908   }
909
910   last_line_was_separator = FALSE;
911
912   if (mode & ERR_SOUND_SERVER)
913     process_name = " sound server";
914   else if (mode & ERR_NETWORK_SERVER)
915     process_name = " network server";
916   else if (mode & ERR_NETWORK_CLIENT)
917     process_name = " network client **";
918
919   if (format)
920   {
921     va_list ap;
922
923     printf_error("%s%s: ", program.command_basename, process_name);
924
925     if (mode & ERR_WARN)
926       printf_error("warning: ");
927
928     va_start(ap, format);
929     vprintf_error_newline(format, ap);
930     va_end(ap);
931   }
932   
933   if (mode & ERR_HELP)
934     printf_error_newline("%s: Try option '--help' for more information.",
935                          program.command_basename);
936
937   if (mode & ERR_EXIT)
938     printf_error_newline("%s%s: aborting",
939                          program.command_basename, process_name);
940
941   if (mode & ERR_EXIT)
942   {
943     if (mode & ERR_FROM_SERVER)
944       exit(1);                          /* child process: normal exit */
945     else
946       program.exit_function(1);         /* main process: clean up stuff */
947   }
948 }
949
950 #else
951
952 void Error(int mode, char *format, ...)
953 {
954   static boolean last_line_was_separator = FALSE;
955   char *process_name = "";
956   FILE *error = stderr;
957   char *newline = "\n";
958
959   /* display warnings only when running in verbose mode */
960   if (mode & ERR_WARN && !options.verbose)
961     return;
962
963   if (mode == ERR_RETURN_LINE)
964   {
965     if (!last_line_was_separator)
966       fprintf_line(error, format, 79);
967
968     last_line_was_separator = TRUE;
969
970     return;
971   }
972
973   last_line_was_separator = FALSE;
974
975 #if defined(PLATFORM_WIN32) || defined(PLATFORM_MSDOS)
976   newline = "\r\n";
977
978   if ((error = openErrorFile()) == NULL)
979   {
980     printf("Cannot write to error output file!%s", newline);
981
982     program.exit_function(1);
983   }
984 #endif
985
986   if (mode & ERR_SOUND_SERVER)
987     process_name = " sound server";
988   else if (mode & ERR_NETWORK_SERVER)
989     process_name = " network server";
990   else if (mode & ERR_NETWORK_CLIENT)
991     process_name = " network client **";
992
993   if (format)
994   {
995     va_list ap;
996
997     fprintf(error, "%s%s: ", program.command_basename, process_name);
998
999     if (mode & ERR_WARN)
1000       fprintf(error, "warning: ");
1001
1002     va_start(ap, format);
1003     vfprintf(error, format, ap);
1004     va_end(ap);
1005   
1006     fprintf(error, "%s", newline);
1007   }
1008   
1009   if (mode & ERR_HELP)
1010     fprintf(error, "%s: Try option '--help' for more information.%s",
1011             program.command_basename, newline);
1012
1013   if (mode & ERR_EXIT)
1014     fprintf(error, "%s%s: aborting%s",
1015             program.command_basename, process_name, newline);
1016
1017   if (error != stderr)
1018     fclose(error);
1019
1020   if (mode & ERR_EXIT)
1021   {
1022     if (mode & ERR_FROM_SERVER)
1023       exit(1);                          /* child process: normal exit */
1024     else
1025       program.exit_function(1);         /* main process: clean up stuff */
1026   }
1027 }
1028
1029 #endif
1030
1031
1032 /* ------------------------------------------------------------------------- */
1033 /* checked memory allocation and freeing functions                           */
1034 /* ------------------------------------------------------------------------- */
1035
1036 void *checked_malloc(unsigned long size)
1037 {
1038   void *ptr;
1039
1040   ptr = malloc(size);
1041
1042   if (ptr == NULL)
1043     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1044
1045   return ptr;
1046 }
1047
1048 void *checked_calloc(unsigned long size)
1049 {
1050   void *ptr;
1051
1052   ptr = calloc(1, size);
1053
1054   if (ptr == NULL)
1055     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1056
1057   return ptr;
1058 }
1059
1060 void *checked_realloc(void *ptr, unsigned long size)
1061 {
1062   ptr = realloc(ptr, size);
1063
1064   if (ptr == NULL)
1065     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
1066
1067   return ptr;
1068 }
1069
1070 void checked_free(void *ptr)
1071 {
1072   if (ptr != NULL)      /* this check should be done by free() anyway */
1073     free(ptr);
1074 }
1075
1076
1077 /* ------------------------------------------------------------------------- */
1078 /* various helper functions                                                  */
1079 /* ------------------------------------------------------------------------- */
1080
1081 inline void swap_numbers(int *i1, int *i2)
1082 {
1083   int help = *i1;
1084
1085   *i1 = *i2;
1086   *i2 = help;
1087 }
1088
1089 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1090 {
1091   int help_x = *x1;
1092   int help_y = *y1;
1093
1094   *x1 = *x2;
1095   *x2 = help_x;
1096
1097   *y1 = *y2;
1098   *y2 = help_y;
1099 }
1100
1101 /* the "put" variants of the following file access functions check for the file
1102    pointer being != NULL and return the number of bytes they have or would have
1103    written; this allows for chunk writing functions to first determine the size
1104    of the (not yet written) chunk, write the correct chunk size and finally
1105    write the chunk itself */
1106
1107 int getFile8BitInteger(FILE *file)
1108 {
1109   return fgetc(file);
1110 }
1111
1112 int putFile8BitInteger(FILE *file, int value)
1113 {
1114   if (file != NULL)
1115     fputc(value, file);
1116
1117   return 1;
1118 }
1119
1120 int getFile16BitInteger(FILE *file, int byte_order)
1121 {
1122   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1123     return ((fgetc(file) << 8) |
1124             (fgetc(file) << 0));
1125   else           /* BYTE_ORDER_LITTLE_ENDIAN */
1126     return ((fgetc(file) << 0) |
1127             (fgetc(file) << 8));
1128 }
1129
1130 int putFile16BitInteger(FILE *file, int value, int byte_order)
1131 {
1132   if (file != NULL)
1133   {
1134     if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1135     {
1136       fputc((value >> 8) & 0xff, file);
1137       fputc((value >> 0) & 0xff, file);
1138     }
1139     else           /* BYTE_ORDER_LITTLE_ENDIAN */
1140     {
1141       fputc((value >> 0) & 0xff, file);
1142       fputc((value >> 8) & 0xff, file);
1143     }
1144   }
1145
1146   return 2;
1147 }
1148
1149 int getFile32BitInteger(FILE *file, int byte_order)
1150 {
1151   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1152     return ((fgetc(file) << 24) |
1153             (fgetc(file) << 16) |
1154             (fgetc(file) <<  8) |
1155             (fgetc(file) <<  0));
1156   else           /* BYTE_ORDER_LITTLE_ENDIAN */
1157     return ((fgetc(file) <<  0) |
1158             (fgetc(file) <<  8) |
1159             (fgetc(file) << 16) |
1160             (fgetc(file) << 24));
1161 }
1162
1163 int putFile32BitInteger(FILE *file, int value, int byte_order)
1164 {
1165   if (file != NULL)
1166   {
1167     if (byte_order == BYTE_ORDER_BIG_ENDIAN)
1168     {
1169       fputc((value >> 24) & 0xff, file);
1170       fputc((value >> 16) & 0xff, file);
1171       fputc((value >>  8) & 0xff, file);
1172       fputc((value >>  0) & 0xff, file);
1173     }
1174     else           /* BYTE_ORDER_LITTLE_ENDIAN */
1175     {
1176       fputc((value >>  0) & 0xff, file);
1177       fputc((value >>  8) & 0xff, file);
1178       fputc((value >> 16) & 0xff, file);
1179       fputc((value >> 24) & 0xff, file);
1180     }
1181   }
1182
1183   return 4;
1184 }
1185
1186 boolean getFileChunk(FILE *file, char *chunk_name, int *chunk_size,
1187                      int byte_order)
1188 {
1189   const int chunk_name_length = 4;
1190
1191   /* read chunk name */
1192   fgets(chunk_name, chunk_name_length + 1, file);
1193
1194   if (chunk_size != NULL)
1195   {
1196     /* read chunk size */
1197     *chunk_size = getFile32BitInteger(file, byte_order);
1198   }
1199
1200   return (feof(file) || ferror(file) ? FALSE : TRUE);
1201 }
1202
1203 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
1204                  int byte_order)
1205 {
1206   int num_bytes = 0;
1207
1208   /* write chunk name */
1209   if (file != NULL)
1210     fputs(chunk_name, file);
1211
1212   num_bytes += strlen(chunk_name);
1213
1214   if (chunk_size >= 0)
1215   {
1216     /* write chunk size */
1217     if (file != NULL)
1218       putFile32BitInteger(file, chunk_size, byte_order);
1219
1220     num_bytes += 4;
1221   }
1222
1223   return num_bytes;
1224 }
1225
1226 int getFileVersion(FILE *file)
1227 {
1228   int version_major = fgetc(file);
1229   int version_minor = fgetc(file);
1230   int version_patch = fgetc(file);
1231   int version_build = fgetc(file);
1232
1233   return VERSION_IDENT(version_major, version_minor, version_patch,
1234                        version_build);
1235 }
1236
1237 int putFileVersion(FILE *file, int version)
1238 {
1239   if (file != NULL)
1240   {
1241     int version_major = VERSION_MAJOR(version);
1242     int version_minor = VERSION_MINOR(version);
1243     int version_patch = VERSION_PATCH(version);
1244     int version_build = VERSION_BUILD(version);
1245
1246     fputc(version_major, file);
1247     fputc(version_minor, file);
1248     fputc(version_patch, file);
1249     fputc(version_build, file);
1250   }
1251
1252   return 4;
1253 }
1254
1255 void ReadBytesFromFile(FILE *file, byte *buffer, unsigned long bytes)
1256 {
1257   int i;
1258
1259   for(i = 0; i < bytes && !feof(file); i++)
1260     buffer[i] = fgetc(file);
1261 }
1262
1263 void WriteBytesToFile(FILE *file, byte *buffer, unsigned long bytes)
1264 {
1265   int i;
1266
1267   for(i = 0; i < bytes; i++)
1268     fputc(buffer[i], file);
1269 }
1270
1271 void ReadUnusedBytesFromFile(FILE *file, unsigned long bytes)
1272 {
1273   while (bytes-- && !feof(file))
1274     fgetc(file);
1275 }
1276
1277 void WriteUnusedBytesToFile(FILE *file, unsigned long bytes)
1278 {
1279   while (bytes--)
1280     fputc(0, file);
1281 }
1282
1283
1284 /* ------------------------------------------------------------------------- */
1285 /* functions to translate key identifiers between different format           */
1286 /* ------------------------------------------------------------------------- */
1287
1288 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
1289 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
1290 #define TRANSLATE_KEYNAME_TO_KEYSYM     2
1291 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  3
1292
1293 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1294 {
1295   static struct
1296   {
1297     Key key;
1298     char *x11name;
1299     char *name;
1300   } translate_key[] =
1301   {
1302     /* normal cursor keys */
1303     { KSYM_Left,        "XK_Left",              "cursor left" },
1304     { KSYM_Right,       "XK_Right",             "cursor right" },
1305     { KSYM_Up,          "XK_Up",                "cursor up" },
1306     { KSYM_Down,        "XK_Down",              "cursor down" },
1307
1308     /* keypad cursor keys */
1309 #ifdef KSYM_KP_Left
1310     { KSYM_KP_Left,     "XK_KP_Left",           "keypad left" },
1311     { KSYM_KP_Right,    "XK_KP_Right",          "keypad right" },
1312     { KSYM_KP_Up,       "XK_KP_Up",             "keypad up" },
1313     { KSYM_KP_Down,     "XK_KP_Down",           "keypad down" },
1314 #endif
1315
1316     /* other keypad keys */
1317 #ifdef KSYM_KP_Enter
1318     { KSYM_KP_Enter,    "XK_KP_Enter",          "keypad enter" },
1319     { KSYM_KP_Add,      "XK_KP_Add",            "keypad +" },
1320     { KSYM_KP_Subtract, "XK_KP_Subtract",       "keypad -" },
1321     { KSYM_KP_Multiply, "XK_KP_Multiply",       "keypad mltply" },
1322     { KSYM_KP_Divide,   "XK_KP_Divide",         "keypad /" },
1323     { KSYM_KP_Separator,"XK_KP_Separator",      "keypad ," },
1324 #endif
1325
1326     /* modifier keys */
1327     { KSYM_Shift_L,     "XK_Shift_L",           "left shift" },
1328     { KSYM_Shift_R,     "XK_Shift_R",           "right shift" },
1329     { KSYM_Control_L,   "XK_Control_L",         "left control" },
1330     { KSYM_Control_R,   "XK_Control_R",         "right control" },
1331     { KSYM_Meta_L,      "XK_Meta_L",            "left meta" },
1332     { KSYM_Meta_R,      "XK_Meta_R",            "right meta" },
1333     { KSYM_Alt_L,       "XK_Alt_L",             "left alt" },
1334     { KSYM_Alt_R,       "XK_Alt_R",             "right alt" },
1335     { KSYM_Super_L,     "XK_Super_L",           "left super" },  /* Win-L */
1336     { KSYM_Super_R,     "XK_Super_R",           "right super" }, /* Win-R */
1337     { KSYM_Mode_switch, "XK_Mode_switch",       "mode switch" }, /* Alt-R */
1338     { KSYM_Multi_key,   "XK_Multi_key",         "multi key" },   /* Ctrl-R */
1339
1340     /* some special keys */
1341     { KSYM_BackSpace,   "XK_BackSpace",         "backspace" },
1342     { KSYM_Delete,      "XK_Delete",            "delete" },
1343     { KSYM_Insert,      "XK_Insert",            "insert" },
1344     { KSYM_Tab,         "XK_Tab",               "tab" },
1345     { KSYM_Home,        "XK_Home",              "home" },
1346     { KSYM_End,         "XK_End",               "end" },
1347     { KSYM_Page_Up,     "XK_Page_Up",           "page up" },
1348     { KSYM_Page_Down,   "XK_Page_Down",         "page down" },
1349     { KSYM_Menu,        "XK_Menu",              "menu" },        /* Win-Menu */
1350
1351     /* ASCII 0x20 to 0x40 keys (except numbers) */
1352     { KSYM_space,       "XK_space",             "space" },
1353     { KSYM_exclam,      "XK_exclam",            "!" },
1354     { KSYM_quotedbl,    "XK_quotedbl",          "\"" },
1355     { KSYM_numbersign,  "XK_numbersign",        "#" },
1356     { KSYM_dollar,      "XK_dollar",            "$" },
1357     { KSYM_percent,     "XK_percent",           "%" },
1358     { KSYM_ampersand,   "XK_ampersand",         "&" },
1359     { KSYM_apostrophe,  "XK_apostrophe",        "'" },
1360     { KSYM_parenleft,   "XK_parenleft",         "(" },
1361     { KSYM_parenright,  "XK_parenright",        ")" },
1362     { KSYM_asterisk,    "XK_asterisk",          "*" },
1363     { KSYM_plus,        "XK_plus",              "+" },
1364     { KSYM_comma,       "XK_comma",             "," },
1365     { KSYM_minus,       "XK_minus",             "-" },
1366     { KSYM_period,      "XK_period",            "." },
1367     { KSYM_slash,       "XK_slash",             "/" },
1368     { KSYM_colon,       "XK_colon",             ":" },
1369     { KSYM_semicolon,   "XK_semicolon",         ";" },
1370     { KSYM_less,        "XK_less",              "<" },
1371     { KSYM_equal,       "XK_equal",             "=" },
1372     { KSYM_greater,     "XK_greater",           ">" },
1373     { KSYM_question,    "XK_question",          "?" },
1374     { KSYM_at,          "XK_at",                "@" },
1375
1376     /* more ASCII keys */
1377     { KSYM_bracketleft, "XK_bracketleft",       "[" },
1378     { KSYM_backslash,   "XK_backslash",         "\\" },
1379     { KSYM_bracketright,"XK_bracketright",      "]" },
1380     { KSYM_asciicircum, "XK_asciicircum",       "^" },
1381     { KSYM_underscore,  "XK_underscore",        "_" },
1382     { KSYM_grave,       "XK_grave",             "grave" },
1383     { KSYM_quoteleft,   "XK_quoteleft",         "quote left" },
1384     { KSYM_braceleft,   "XK_braceleft",         "brace left" },
1385     { KSYM_bar,         "XK_bar",               "bar" },
1386     { KSYM_braceright,  "XK_braceright",        "brace right" },
1387     { KSYM_asciitilde,  "XK_asciitilde",        "~" },
1388
1389     /* special (non-ASCII) keys */
1390     { KSYM_Adiaeresis,  "XK_Adiaeresis",        "Ä" },
1391     { KSYM_Odiaeresis,  "XK_Odiaeresis",        "Ö" },
1392     { KSYM_Udiaeresis,  "XK_Udiaeresis",        "Ãœ" },
1393     { KSYM_adiaeresis,  "XK_adiaeresis",        "ä" },
1394     { KSYM_odiaeresis,  "XK_odiaeresis",        "ö" },
1395     { KSYM_udiaeresis,  "XK_udiaeresis",        "ü" },
1396     { KSYM_ssharp,      "XK_ssharp",            "sharp s" },
1397
1398     /* end-of-array identifier */
1399     { 0,                NULL,                   NULL }
1400   };
1401
1402   int i;
1403
1404   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1405   {
1406     static char name_buffer[30];
1407     Key key = *keysym;
1408
1409     if (key >= KSYM_A && key <= KSYM_Z)
1410       sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1411     else if (key >= KSYM_a && key <= KSYM_z)
1412       sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1413     else if (key >= KSYM_0 && key <= KSYM_9)
1414       sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1415     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1416       sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1417 #if 1
1418     else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1419       sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1420 #else
1421     else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1422       sprintf(name_buffer, "function F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1423 #endif
1424     else if (key == KSYM_UNDEFINED)
1425       strcpy(name_buffer, "(undefined)");
1426     else
1427     {
1428       i = 0;
1429
1430       do
1431       {
1432         if (key == translate_key[i].key)
1433         {
1434           strcpy(name_buffer, translate_key[i].name);
1435           break;
1436         }
1437       }
1438       while (translate_key[++i].name);
1439
1440       if (!translate_key[i].name)
1441         strcpy(name_buffer, "(unknown)");
1442     }
1443
1444     *name = name_buffer;
1445   }
1446   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1447   {
1448     static char name_buffer[30];
1449     Key key = *keysym;
1450
1451     if (key >= KSYM_A && key <= KSYM_Z)
1452       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1453     else if (key >= KSYM_a && key <= KSYM_z)
1454       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1455     else if (key >= KSYM_0 && key <= KSYM_9)
1456       sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1457     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1458       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1459     else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1460       sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1461     else if (key == KSYM_UNDEFINED)
1462       strcpy(name_buffer, "[undefined]");
1463     else
1464     {
1465       i = 0;
1466
1467       do
1468       {
1469         if (key == translate_key[i].key)
1470         {
1471           strcpy(name_buffer, translate_key[i].x11name);
1472           break;
1473         }
1474       }
1475       while (translate_key[++i].x11name);
1476
1477       if (!translate_key[i].x11name)
1478         sprintf(name_buffer, "0x%04lx", (unsigned long)key);
1479     }
1480
1481     *x11name = name_buffer;
1482   }
1483   else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1484   {
1485     Key key = KSYM_UNDEFINED;
1486
1487     i = 0;
1488     do
1489     {
1490       if (strEqual(translate_key[i].name, *name))
1491       {
1492         key = translate_key[i].key;
1493         break;
1494       }
1495     }
1496     while (translate_key[++i].x11name);
1497
1498     if (key == KSYM_UNDEFINED)
1499       Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1500
1501     *keysym = key;
1502   }
1503   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1504   {
1505     Key key = KSYM_UNDEFINED;
1506     char *name_ptr = *x11name;
1507
1508     if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
1509     {
1510       char c = name_ptr[3];
1511
1512       if (c >= 'A' && c <= 'Z')
1513         key = KSYM_A + (Key)(c - 'A');
1514       else if (c >= 'a' && c <= 'z')
1515         key = KSYM_a + (Key)(c - 'a');
1516       else if (c >= '0' && c <= '9')
1517         key = KSYM_0 + (Key)(c - '0');
1518     }
1519     else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
1520     {
1521       char c = name_ptr[6];
1522
1523       if (c >= '0' && c <= '9')
1524         key = KSYM_KP_0 + (Key)(c - '0');
1525     }
1526     else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
1527     {
1528       char c1 = name_ptr[4];
1529       char c2 = name_ptr[5];
1530       int d = 0;
1531
1532       if ((c1 >= '0' && c1 <= '9') &&
1533           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1534         d = atoi(&name_ptr[4]);
1535
1536       if (d >= 1 && d <= KSYM_NUM_FKEYS)
1537         key = KSYM_F1 + (Key)(d - 1);
1538     }
1539     else if (strncmp(name_ptr, "XK_", 3) == 0)
1540     {
1541       i = 0;
1542
1543       do
1544       {
1545         if (strEqual(name_ptr, translate_key[i].x11name))
1546         {
1547           key = translate_key[i].key;
1548           break;
1549         }
1550       }
1551       while (translate_key[++i].x11name);
1552     }
1553     else if (strncmp(name_ptr, "0x", 2) == 0)
1554     {
1555       unsigned long value = 0;
1556
1557       name_ptr += 2;
1558
1559       while (name_ptr)
1560       {
1561         char c = *name_ptr++;
1562         int d = -1;
1563
1564         if (c >= '0' && c <= '9')
1565           d = (int)(c - '0');
1566         else if (c >= 'a' && c <= 'f')
1567           d = (int)(c - 'a' + 10);
1568         else if (c >= 'A' && c <= 'F')
1569           d = (int)(c - 'A' + 10);
1570
1571         if (d == -1)
1572         {
1573           value = -1;
1574           break;
1575         }
1576
1577         value = value * 16 + d;
1578       }
1579
1580       if (value != -1)
1581         key = (Key)value;
1582     }
1583
1584     *keysym = key;
1585   }
1586 }
1587
1588 char *getKeyNameFromKey(Key key)
1589 {
1590   char *name;
1591
1592   translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1593   return name;
1594 }
1595
1596 char *getX11KeyNameFromKey(Key key)
1597 {
1598   char *x11name;
1599
1600   translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1601   return x11name;
1602 }
1603
1604 Key getKeyFromKeyName(char *name)
1605 {
1606   Key key;
1607
1608   translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1609   return key;
1610 }
1611
1612 Key getKeyFromX11KeyName(char *x11name)
1613 {
1614   Key key;
1615
1616   translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1617   return key;
1618 }
1619
1620 char getCharFromKey(Key key)
1621 {
1622   char *keyname = getKeyNameFromKey(key);
1623   char letter = 0;
1624
1625   if (strlen(keyname) == 1)
1626     letter = keyname[0];
1627   else if (strEqual(keyname, "space"))
1628     letter = ' ';
1629   else if (strEqual(keyname, "circumflex"))
1630     letter = '^';
1631
1632   return letter;
1633 }
1634
1635
1636 /* ------------------------------------------------------------------------- */
1637 /* functions to translate string identifiers to integer or boolean value     */
1638 /* ------------------------------------------------------------------------- */
1639
1640 int get_integer_from_string(char *s)
1641 {
1642   static char *number_text[][3] =
1643   {
1644     { "0",      "zero",         "null",         },
1645     { "1",      "one",          "first"         },
1646     { "2",      "two",          "second"        },
1647     { "3",      "three",        "third"         },
1648     { "4",      "four",         "fourth"        },
1649     { "5",      "five",         "fifth"         },
1650     { "6",      "six",          "sixth"         },
1651     { "7",      "seven",        "seventh"       },
1652     { "8",      "eight",        "eighth"        },
1653     { "9",      "nine",         "ninth"         },
1654     { "10",     "ten",          "tenth"         },
1655     { "11",     "eleven",       "eleventh"      },
1656     { "12",     "twelve",       "twelfth"       },
1657
1658     { NULL,     NULL,           NULL            },
1659   };
1660
1661   int i, j;
1662   char *s_lower = getStringToLower(s);
1663   int result = -1;
1664
1665   for (i = 0; number_text[i][0] != NULL; i++)
1666     for (j = 0; j < 3; j++)
1667       if (strEqual(s_lower, number_text[i][j]))
1668         result = i;
1669
1670   if (result == -1)
1671   {
1672     if (strEqual(s_lower, "false"))
1673       result = 0;
1674     else if (strEqual(s_lower, "true"))
1675       result = 1;
1676     else
1677       result = atoi(s);
1678   }
1679
1680   free(s_lower);
1681
1682   return result;
1683 }
1684
1685 boolean get_boolean_from_string(char *s)
1686 {
1687   char *s_lower = getStringToLower(s);
1688   boolean result = FALSE;
1689
1690   if (strEqual(s_lower, "true") ||
1691       strEqual(s_lower, "yes") ||
1692       strEqual(s_lower, "on") ||
1693       get_integer_from_string(s) == 1)
1694     result = TRUE;
1695
1696   free(s_lower);
1697
1698   return result;
1699 }
1700
1701
1702 /* ------------------------------------------------------------------------- */
1703 /* functions for generic lists                                               */
1704 /* ------------------------------------------------------------------------- */
1705
1706 ListNode *newListNode()
1707 {
1708   return checked_calloc(sizeof(ListNode));
1709 }
1710
1711 void addNodeToList(ListNode **node_first, char *key, void *content)
1712 {
1713   ListNode *node_new = newListNode();
1714
1715   node_new->key = getStringCopy(key);
1716   node_new->content = content;
1717   node_new->next = *node_first;
1718   *node_first = node_new;
1719 }
1720
1721 void deleteNodeFromList(ListNode **node_first, char *key,
1722                         void (*destructor_function)(void *))
1723 {
1724   if (node_first == NULL || *node_first == NULL)
1725     return;
1726
1727   if (strEqual((*node_first)->key, key))
1728   {
1729     free((*node_first)->key);
1730     if (destructor_function)
1731       destructor_function((*node_first)->content);
1732     *node_first = (*node_first)->next;
1733   }
1734   else
1735     deleteNodeFromList(&(*node_first)->next, key, destructor_function);
1736 }
1737
1738 ListNode *getNodeFromKey(ListNode *node_first, char *key)
1739 {
1740   if (node_first == NULL)
1741     return NULL;
1742
1743   if (strEqual(node_first->key, key))
1744     return node_first;
1745   else
1746     return getNodeFromKey(node_first->next, key);
1747 }
1748
1749 int getNumNodes(ListNode *node_first)
1750 {
1751   return (node_first ? 1 + getNumNodes(node_first->next) : 0);
1752 }
1753
1754 void dumpList(ListNode *node_first)
1755 {
1756   ListNode *node = node_first;
1757
1758   while (node)
1759   {
1760     printf("['%s' (%d)]\n", node->key,
1761            ((struct ListNodeInfo *)node->content)->num_references);
1762     node = node->next;
1763   }
1764
1765   printf("[%d nodes]\n", getNumNodes(node_first));
1766 }
1767
1768
1769 /* ------------------------------------------------------------------------- */
1770 /* functions for checking files and filenames                                */
1771 /* ------------------------------------------------------------------------- */
1772
1773 boolean fileExists(char *filename)
1774 {
1775   if (filename == NULL)
1776     return FALSE;
1777
1778   return (access(filename, F_OK) == 0);
1779 }
1780
1781 boolean fileHasPrefix(char *basename, char *prefix)
1782 {
1783   static char *basename_lower = NULL;
1784   int basename_length, prefix_length;
1785
1786   checked_free(basename_lower);
1787
1788   if (basename == NULL || prefix == NULL)
1789     return FALSE;
1790
1791   basename_lower = getStringToLower(basename);
1792   basename_length = strlen(basename_lower);
1793   prefix_length = strlen(prefix);
1794
1795   if (basename_length > prefix_length + 1 &&
1796       basename_lower[prefix_length] == '.' &&
1797       strncmp(basename_lower, prefix, prefix_length) == 0)
1798     return TRUE;
1799
1800   return FALSE;
1801 }
1802
1803 boolean fileHasSuffix(char *basename, char *suffix)
1804 {
1805   static char *basename_lower = NULL;
1806   int basename_length, suffix_length;
1807
1808   checked_free(basename_lower);
1809
1810   if (basename == NULL || suffix == NULL)
1811     return FALSE;
1812
1813   basename_lower = getStringToLower(basename);
1814   basename_length = strlen(basename_lower);
1815   suffix_length = strlen(suffix);
1816
1817   if (basename_length > suffix_length + 1 &&
1818       basename_lower[basename_length - suffix_length - 1] == '.' &&
1819       strEqual(&basename_lower[basename_length - suffix_length], suffix))
1820     return TRUE;
1821
1822   return FALSE;
1823 }
1824
1825 boolean FileIsGraphic(char *filename)
1826 {
1827   char *basename = getBaseNamePtr(filename);
1828
1829   return fileHasSuffix(basename, "pcx");
1830 }
1831
1832 boolean FileIsSound(char *filename)
1833 {
1834   char *basename = getBaseNamePtr(filename);
1835
1836   return fileHasSuffix(basename, "wav");
1837 }
1838
1839 boolean FileIsMusic(char *filename)
1840 {
1841   char *basename = getBaseNamePtr(filename);
1842
1843   if (FileIsSound(basename))
1844     return TRUE;
1845
1846 #if defined(TARGET_SDL)
1847   if (fileHasPrefix(basename, "mod") ||
1848       fileHasSuffix(basename, "mod") ||
1849       fileHasSuffix(basename, "s3m") ||
1850       fileHasSuffix(basename, "it") ||
1851       fileHasSuffix(basename, "xm") ||
1852       fileHasSuffix(basename, "midi") ||
1853       fileHasSuffix(basename, "mid") ||
1854       fileHasSuffix(basename, "mp3") ||
1855       fileHasSuffix(basename, "ogg"))
1856     return TRUE;
1857 #endif
1858
1859   return FALSE;
1860 }
1861
1862 boolean FileIsArtworkType(char *basename, int type)
1863 {
1864   if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(basename)) ||
1865       (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(basename)) ||
1866       (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(basename)))
1867     return TRUE;
1868
1869   return FALSE;
1870 }
1871
1872 /* ------------------------------------------------------------------------- */
1873 /* functions for loading artwork configuration information                   */
1874 /* ------------------------------------------------------------------------- */
1875
1876 char *get_mapped_token(char *token)
1877 {
1878   /* !!! make this dynamically configurable (init.c:InitArtworkConfig) !!! */
1879   static char *map_token_prefix[][2] =
1880   {
1881     { "char_procent",           "char_percent"  },
1882     { NULL,                                     }
1883   };
1884   int i;
1885
1886   for (i = 0; map_token_prefix[i][0] != NULL; i++)
1887   {
1888     int len_token_prefix = strlen(map_token_prefix[i][0]);
1889
1890     if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
1891       return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
1892   }
1893
1894   return NULL;
1895 }
1896
1897 /* This function checks if a string <s> of the format "string1, string2, ..."
1898    exactly contains a string <s_contained>. */
1899
1900 static boolean string_has_parameter(char *s, char *s_contained)
1901 {
1902   char *substring;
1903
1904   if (s == NULL || s_contained == NULL)
1905     return FALSE;
1906
1907   if (strlen(s_contained) > strlen(s))
1908     return FALSE;
1909
1910   if (strncmp(s, s_contained, strlen(s_contained)) == 0)
1911   {
1912     char next_char = s[strlen(s_contained)];
1913
1914     /* check if next character is delimiter or whitespace */
1915     return (next_char == ',' || next_char == '\0' ||
1916             next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
1917   }
1918
1919   /* check if string contains another parameter string after a comma */
1920   substring = strchr(s, ',');
1921   if (substring == NULL)        /* string does not contain a comma */
1922     return FALSE;
1923
1924   /* advance string pointer to next character after the comma */
1925   substring++;
1926
1927   /* skip potential whitespaces after the comma */
1928   while (*substring == ' ' || *substring == '\t')
1929     substring++;
1930
1931   return string_has_parameter(substring, s_contained);
1932 }
1933
1934 int get_parameter_value(char *value_raw, char *suffix, int type)
1935 {
1936   char *value = getStringToLower(value_raw);
1937   int result = 0;       /* probably a save default value */
1938
1939   if (strEqual(suffix, ".direction"))
1940   {
1941     result = (strEqual(value, "left")  ? MV_LEFT :
1942               strEqual(value, "right") ? MV_RIGHT :
1943               strEqual(value, "up")    ? MV_UP :
1944               strEqual(value, "down")  ? MV_DOWN : MV_NONE);
1945   }
1946   else if (strEqual(suffix, ".anim_mode"))
1947   {
1948     result = (string_has_parameter(value, "none")       ? ANIM_NONE :
1949               string_has_parameter(value, "loop")       ? ANIM_LOOP :
1950               string_has_parameter(value, "linear")     ? ANIM_LINEAR :
1951               string_has_parameter(value, "pingpong")   ? ANIM_PINGPONG :
1952               string_has_parameter(value, "pingpong2")  ? ANIM_PINGPONG2 :
1953               string_has_parameter(value, "random")     ? ANIM_RANDOM :
1954               string_has_parameter(value, "ce_value")   ? ANIM_CE_VALUE :
1955               string_has_parameter(value, "ce_score")   ? ANIM_CE_SCORE :
1956               string_has_parameter(value, "ce_delay")   ? ANIM_CE_DELAY :
1957               string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
1958               string_has_parameter(value, "vertical")   ? ANIM_VERTICAL :
1959               ANIM_DEFAULT);
1960
1961     if (string_has_parameter(value, "reverse"))
1962       result |= ANIM_REVERSE;
1963
1964     if (string_has_parameter(value, "opaque_player"))
1965       result |= ANIM_OPAQUE_PLAYER;
1966
1967     if (string_has_parameter(value, "static_panel"))
1968       result |= ANIM_STATIC_PANEL;
1969   }
1970   else          /* generic parameter of type integer or boolean */
1971   {
1972     result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
1973               type == TYPE_INTEGER ? get_integer_from_string(value) :
1974               type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
1975               ARG_UNDEFINED_VALUE);
1976   }
1977
1978   free(value);
1979
1980   return result;
1981 }
1982
1983 int get_auto_parameter_value(char *token, char *value_raw)
1984 {
1985   char *suffix;
1986
1987   if (token == NULL || value_raw == NULL)
1988     return ARG_UNDEFINED_VALUE;
1989
1990   suffix = strrchr(token, '.');
1991   if (suffix == NULL)
1992     suffix = token;
1993
1994   return get_parameter_value(value_raw, suffix, TYPE_INTEGER);
1995 }
1996
1997 static void FreeCustomArtworkList(struct ArtworkListInfo *,
1998                                   struct ListNodeInfo ***, int *);
1999
2000 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
2001                                            struct ConfigTypeInfo *suffix_list,
2002                                            char **ignore_tokens,
2003                                            int num_file_list_entries)
2004 {
2005   struct FileInfo *file_list;
2006   int num_file_list_entries_found = 0;
2007   int num_suffix_list_entries = 0;
2008   int list_pos;
2009   int i, j;
2010
2011   file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
2012
2013   for (i = 0; suffix_list[i].token != NULL; i++)
2014     num_suffix_list_entries++;
2015
2016   /* always start with reliable default values */
2017   for (i = 0; i < num_file_list_entries; i++)
2018   {
2019     file_list[i].token = NULL;
2020
2021     file_list[i].default_filename = NULL;
2022     file_list[i].filename = NULL;
2023
2024     if (num_suffix_list_entries > 0)
2025     {
2026       int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2027
2028       file_list[i].default_parameter = checked_calloc(parameter_array_size);
2029       file_list[i].parameter = checked_calloc(parameter_array_size);
2030
2031       for (j = 0; j < num_suffix_list_entries; j++)
2032       {
2033         setString(&file_list[i].default_parameter[j], suffix_list[j].value);
2034         setString(&file_list[i].parameter[j], suffix_list[j].value);
2035       }
2036
2037       file_list[i].redefined = FALSE;
2038       file_list[i].fallback_to_default = FALSE;
2039     }
2040   }
2041
2042   list_pos = 0;
2043   for (i = 0; config_list[i].token != NULL; i++)
2044   {
2045     int len_config_token = strlen(config_list[i].token);
2046     int len_config_value = strlen(config_list[i].value);
2047     boolean is_file_entry = TRUE;
2048
2049     for (j = 0; suffix_list[j].token != NULL; j++)
2050     {
2051       int len_suffix = strlen(suffix_list[j].token);
2052
2053       if (len_suffix < len_config_token &&
2054           strEqual(&config_list[i].token[len_config_token - len_suffix],
2055                    suffix_list[j].token))
2056       {
2057         setString(&file_list[list_pos].default_parameter[j],
2058                   config_list[i].value);
2059
2060         is_file_entry = FALSE;
2061         break;
2062       }
2063     }
2064
2065     /* the following tokens are no file definitions, but other config tokens */
2066     for (j = 0; ignore_tokens[j] != NULL; j++)
2067       if (strEqual(config_list[i].token, ignore_tokens[j]))
2068         is_file_entry = FALSE;
2069
2070     if (is_file_entry)
2071     {
2072       if (i > 0)
2073         list_pos++;
2074
2075       if (list_pos >= num_file_list_entries)
2076         break;
2077
2078       /* simple sanity check if this is really a file definition */
2079       if (!strEqual(&config_list[i].value[len_config_value - 4], ".pcx") &&
2080           !strEqual(&config_list[i].value[len_config_value - 4], ".wav") &&
2081           !strEqual(config_list[i].value, UNDEFINED_FILENAME))
2082       {
2083         Error(ERR_RETURN, "Configuration directive '%s' -> '%s':",
2084               config_list[i].token, config_list[i].value);
2085         Error(ERR_EXIT, "This seems to be no valid definition -- please fix");
2086       }
2087
2088       file_list[list_pos].token = config_list[i].token;
2089       file_list[list_pos].default_filename = config_list[i].value;
2090     }
2091   }
2092
2093   num_file_list_entries_found = list_pos + 1;
2094   if (num_file_list_entries_found != num_file_list_entries)
2095   {
2096     Error(ERR_RETURN_LINE, "-");
2097     Error(ERR_RETURN, "inconsistant config list information:");
2098     Error(ERR_RETURN, "- should be:   %d (according to 'src/conf_gfx.h')",
2099           num_file_list_entries);
2100     Error(ERR_RETURN, "- found to be: %d (according to 'src/conf_gfx.c')",
2101           num_file_list_entries_found);
2102     Error(ERR_EXIT,   "please fix");
2103   }
2104
2105   return file_list;
2106 }
2107
2108 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
2109 {
2110   int len_token = strlen(token);
2111   int len_suffix = strlen(suffix);
2112
2113   if (start_pos < 0)    /* compare suffix from end of string */
2114     start_pos += len_token;
2115
2116   if (start_pos < 0 || start_pos + len_suffix > len_token)
2117     return FALSE;
2118
2119   if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
2120     return FALSE;
2121
2122   if (token[start_pos + len_suffix] == '\0')
2123     return TRUE;
2124
2125   if (token[start_pos + len_suffix] == '.')
2126     return TRUE;
2127
2128   return FALSE;
2129 }
2130
2131 #define KNOWN_TOKEN_VALUE       "[KNOWN_TOKEN_VALUE]"
2132
2133 static void read_token_parameters(SetupFileHash *setup_file_hash,
2134                                   struct ConfigTypeInfo *suffix_list,
2135                                   struct FileInfo *file_list_entry)
2136 {
2137   /* check for config token that is the base token without any suffixes */
2138   char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
2139   char *known_token_value = KNOWN_TOKEN_VALUE;
2140   int i;
2141
2142   if (filename != NULL)
2143   {
2144     setString(&file_list_entry->filename, filename);
2145
2146     /* when file definition found, set all parameters to default values */
2147     for (i = 0; suffix_list[i].token != NULL; i++)
2148       setString(&file_list_entry->parameter[i], suffix_list[i].value);
2149
2150     file_list_entry->redefined = TRUE;
2151
2152     /* mark config file token as well known from default config */
2153     setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
2154   }
2155
2156   /* check for config tokens that can be build by base token and suffixes */
2157   for (i = 0; suffix_list[i].token != NULL; i++)
2158   {
2159     char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
2160     char *value = getHashEntry(setup_file_hash, token);
2161
2162     if (value != NULL)
2163     {
2164       setString(&file_list_entry->parameter[i], value);
2165
2166       /* mark config file token as well known from default config */
2167       setHashEntry(setup_file_hash, token, known_token_value);
2168     }
2169
2170     free(token);
2171   }
2172 }
2173
2174 static void add_dynamic_file_list_entry(struct FileInfo **list,
2175                                         int *num_list_entries,
2176                                         SetupFileHash *extra_file_hash,
2177                                         struct ConfigTypeInfo *suffix_list,
2178                                         int num_suffix_list_entries,
2179                                         char *token)
2180 {
2181   struct FileInfo *new_list_entry;
2182   int parameter_array_size = num_suffix_list_entries * sizeof(char *);
2183
2184   (*num_list_entries)++;
2185   *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
2186   new_list_entry = &(*list)[*num_list_entries - 1];
2187
2188   new_list_entry->token = getStringCopy(token);
2189   new_list_entry->default_filename = NULL;
2190   new_list_entry->filename = NULL;
2191   new_list_entry->parameter = checked_calloc(parameter_array_size);
2192
2193   new_list_entry->redefined = FALSE;
2194   new_list_entry->fallback_to_default = FALSE;
2195
2196   read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
2197 }
2198
2199 static void add_property_mapping(struct PropertyMapping **list,
2200                                  int *num_list_entries,
2201                                  int base_index, int ext1_index,
2202                                  int ext2_index, int ext3_index,
2203                                  int artwork_index)
2204 {
2205   struct PropertyMapping *new_list_entry;
2206
2207   (*num_list_entries)++;
2208   *list = checked_realloc(*list,
2209                           *num_list_entries * sizeof(struct PropertyMapping));
2210   new_list_entry = &(*list)[*num_list_entries - 1];
2211
2212   new_list_entry->base_index = base_index;
2213   new_list_entry->ext1_index = ext1_index;
2214   new_list_entry->ext2_index = ext2_index;
2215   new_list_entry->ext3_index = ext3_index;
2216
2217   new_list_entry->artwork_index = artwork_index;
2218 }
2219
2220 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
2221                                           char *filename)
2222 {
2223   struct FileInfo *file_list = artwork_info->file_list;
2224   struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
2225   char **base_prefixes = artwork_info->base_prefixes;
2226   char **ext1_suffixes = artwork_info->ext1_suffixes;
2227   char **ext2_suffixes = artwork_info->ext2_suffixes;
2228   char **ext3_suffixes = artwork_info->ext3_suffixes;
2229   char **ignore_tokens = artwork_info->ignore_tokens;
2230   int num_file_list_entries = artwork_info->num_file_list_entries;
2231   int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
2232   int num_base_prefixes = artwork_info->num_base_prefixes;
2233   int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
2234   int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
2235   int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
2236   int num_ignore_tokens = artwork_info->num_ignore_tokens;
2237   SetupFileHash *setup_file_hash, *valid_file_hash;
2238   SetupFileHash *extra_file_hash, *empty_file_hash;
2239   char *known_token_value = KNOWN_TOKEN_VALUE;
2240   int i, j, k, l;
2241
2242   if (filename == NULL)
2243     return;
2244
2245 #if 0
2246   printf("LoadArtworkConfigFromFilename '%s' ...\n", filename);
2247 #endif
2248
2249   if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
2250     return;
2251
2252   /* separate valid (defined) from empty (undefined) config token values */
2253   valid_file_hash = newSetupFileHash();
2254   empty_file_hash = newSetupFileHash();
2255   BEGIN_HASH_ITERATION(setup_file_hash, itr)
2256   {
2257     char *value = HASH_ITERATION_VALUE(itr);
2258
2259     setHashEntry(*value ? valid_file_hash : empty_file_hash,
2260                  HASH_ITERATION_TOKEN(itr), value);
2261   }
2262   END_HASH_ITERATION(setup_file_hash, itr)
2263
2264   /* at this point, we do not need the setup file hash anymore -- free it */
2265   freeSetupFileHash(setup_file_hash);
2266
2267   /* map deprecated to current tokens (using prefix match and replace) */
2268   BEGIN_HASH_ITERATION(valid_file_hash, itr)
2269   {
2270     char *token = HASH_ITERATION_TOKEN(itr);
2271     char *mapped_token = get_mapped_token(token);
2272
2273     if (mapped_token != NULL)
2274     {
2275       char *value = HASH_ITERATION_VALUE(itr);
2276
2277       /* add mapped token */
2278       setHashEntry(valid_file_hash, mapped_token, value);
2279
2280       /* ignore old token (by setting it to "known" keyword) */
2281       setHashEntry(valid_file_hash, token, known_token_value);
2282
2283       free(mapped_token);
2284     }
2285   }
2286   END_HASH_ITERATION(valid_file_hash, itr)
2287
2288   /* read parameters for all known config file tokens */
2289   for (i = 0; i < num_file_list_entries; i++)
2290     read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
2291
2292   /* set all tokens that can be ignored here to "known" keyword */
2293   for (i = 0; i < num_ignore_tokens; i++)
2294     setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
2295
2296   /* copy all unknown config file tokens to extra config hash */
2297   extra_file_hash = newSetupFileHash();
2298   BEGIN_HASH_ITERATION(valid_file_hash, itr)
2299   {
2300     char *value = HASH_ITERATION_VALUE(itr);
2301
2302     if (!strEqual(value, known_token_value))
2303       setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
2304   }
2305   END_HASH_ITERATION(valid_file_hash, itr)
2306
2307   /* at this point, we do not need the valid file hash anymore -- free it */
2308   freeSetupFileHash(valid_file_hash);
2309
2310   /* now try to determine valid, dynamically defined config tokens */
2311
2312   BEGIN_HASH_ITERATION(extra_file_hash, itr)
2313   {
2314     struct FileInfo **dynamic_file_list =
2315       &artwork_info->dynamic_file_list;
2316     int *num_dynamic_file_list_entries =
2317       &artwork_info->num_dynamic_file_list_entries;
2318     struct PropertyMapping **property_mapping =
2319       &artwork_info->property_mapping;
2320     int *num_property_mapping_entries =
2321       &artwork_info->num_property_mapping_entries;
2322     int current_summarized_file_list_entry =
2323       artwork_info->num_file_list_entries +
2324       artwork_info->num_dynamic_file_list_entries;
2325     char *token = HASH_ITERATION_TOKEN(itr);
2326     int len_token = strlen(token);
2327     int start_pos;
2328     boolean base_prefix_found = FALSE;
2329     boolean parameter_suffix_found = FALSE;
2330
2331 #if 0
2332     printf("::: examining '%s' -> '%s'\n", token, HASH_ITERATION_VALUE(itr));
2333 #endif
2334
2335     /* skip all parameter definitions (handled by read_token_parameters()) */
2336     for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
2337     {
2338       int len_suffix = strlen(suffix_list[i].token);
2339
2340       if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
2341         parameter_suffix_found = TRUE;
2342     }
2343
2344     if (parameter_suffix_found)
2345       continue;
2346
2347     /* ---------- step 0: search for matching base prefix ---------- */
2348
2349     start_pos = 0;
2350     for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
2351     {
2352       char *base_prefix = base_prefixes[i];
2353       int len_base_prefix = strlen(base_prefix);
2354       boolean ext1_suffix_found = FALSE;
2355       boolean ext2_suffix_found = FALSE;
2356       boolean ext3_suffix_found = FALSE;
2357       boolean exact_match = FALSE;
2358       int base_index = -1;
2359       int ext1_index = -1;
2360       int ext2_index = -1;
2361       int ext3_index = -1;
2362
2363       base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
2364
2365       if (!base_prefix_found)
2366         continue;
2367
2368       base_index = i;
2369
2370       if (start_pos + len_base_prefix == len_token)     /* exact match */
2371       {
2372         exact_match = TRUE;
2373
2374         add_dynamic_file_list_entry(dynamic_file_list,
2375                                     num_dynamic_file_list_entries,
2376                                     extra_file_hash,
2377                                     suffix_list,
2378                                     num_suffix_list_entries,
2379                                     token);
2380         add_property_mapping(property_mapping,
2381                              num_property_mapping_entries,
2382                              base_index, -1, -1, -1,
2383                              current_summarized_file_list_entry);
2384         continue;
2385       }
2386
2387 #if 0
2388       if (IS_PARENT_PROCESS())
2389         printf("---> examining token '%s': search 1st suffix ...\n", token);
2390 #endif
2391
2392       /* ---------- step 1: search for matching first suffix ---------- */
2393
2394       start_pos += len_base_prefix;
2395       for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
2396       {
2397         char *ext1_suffix = ext1_suffixes[j];
2398         int len_ext1_suffix = strlen(ext1_suffix);
2399
2400         ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
2401
2402         if (!ext1_suffix_found)
2403           continue;
2404
2405         ext1_index = j;
2406
2407         if (start_pos + len_ext1_suffix == len_token)   /* exact match */
2408         {
2409           exact_match = TRUE;
2410
2411           add_dynamic_file_list_entry(dynamic_file_list,
2412                                       num_dynamic_file_list_entries,
2413                                       extra_file_hash,
2414                                       suffix_list,
2415                                       num_suffix_list_entries,
2416                                       token);
2417           add_property_mapping(property_mapping,
2418                                num_property_mapping_entries,
2419                                base_index, ext1_index, -1, -1,
2420                                current_summarized_file_list_entry);
2421           continue;
2422         }
2423
2424         start_pos += len_ext1_suffix;
2425       }
2426
2427       if (exact_match)
2428         break;
2429
2430 #if 0
2431       if (IS_PARENT_PROCESS())
2432         printf("---> examining token '%s': search 2nd suffix ...\n", token);
2433 #endif
2434
2435       /* ---------- step 2: search for matching second suffix ---------- */
2436
2437       for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
2438       {
2439         char *ext2_suffix = ext2_suffixes[k];
2440         int len_ext2_suffix = strlen(ext2_suffix);
2441
2442         ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
2443
2444         if (!ext2_suffix_found)
2445           continue;
2446
2447         ext2_index = k;
2448
2449         if (start_pos + len_ext2_suffix == len_token)   /* exact match */
2450         {
2451           exact_match = TRUE;
2452
2453           add_dynamic_file_list_entry(dynamic_file_list,
2454                                       num_dynamic_file_list_entries,
2455                                       extra_file_hash,
2456                                       suffix_list,
2457                                       num_suffix_list_entries,
2458                                       token);
2459           add_property_mapping(property_mapping,
2460                                num_property_mapping_entries,
2461                                base_index, ext1_index, ext2_index, -1,
2462                                current_summarized_file_list_entry);
2463           continue;
2464         }
2465
2466         start_pos += len_ext2_suffix;
2467       }
2468
2469       if (exact_match)
2470         break;
2471
2472 #if 0
2473       if (IS_PARENT_PROCESS())
2474         printf("---> examining token '%s': search 3rd suffix ...\n",token);
2475 #endif
2476
2477       /* ---------- step 3: search for matching third suffix ---------- */
2478
2479       for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
2480       {
2481         char *ext3_suffix = ext3_suffixes[l];
2482         int len_ext3_suffix = strlen(ext3_suffix);
2483
2484         ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
2485
2486         if (!ext3_suffix_found)
2487           continue;
2488
2489         ext3_index = l;
2490
2491         if (start_pos + len_ext3_suffix == len_token) /* exact match */
2492         {
2493           exact_match = TRUE;
2494
2495           add_dynamic_file_list_entry(dynamic_file_list,
2496                                       num_dynamic_file_list_entries,
2497                                       extra_file_hash,
2498                                       suffix_list,
2499                                       num_suffix_list_entries,
2500                                       token);
2501           add_property_mapping(property_mapping,
2502                                num_property_mapping_entries,
2503                                base_index, ext1_index, ext2_index, ext3_index,
2504                                current_summarized_file_list_entry);
2505           continue;
2506         }
2507       }
2508     }
2509   }
2510   END_HASH_ITERATION(extra_file_hash, itr)
2511
2512   if (artwork_info->num_dynamic_file_list_entries > 0)
2513   {
2514     artwork_info->dynamic_artwork_list =
2515       checked_calloc(artwork_info->num_dynamic_file_list_entries *
2516                      artwork_info->sizeof_artwork_list_entry);
2517   }
2518
2519   if (options.verbose && IS_PARENT_PROCESS())
2520   {
2521     SetupFileList *setup_file_list, *list;
2522     boolean dynamic_tokens_found = FALSE;
2523     boolean unknown_tokens_found = FALSE;
2524     boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
2525
2526     if ((setup_file_list = loadSetupFileList(filename)) == NULL)
2527       Error(ERR_EXIT, "loadSetupFileHash works, but loadSetupFileList fails");
2528
2529     BEGIN_HASH_ITERATION(extra_file_hash, itr)
2530     {
2531       if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
2532         dynamic_tokens_found = TRUE;
2533       else
2534         unknown_tokens_found = TRUE;
2535     }
2536     END_HASH_ITERATION(extra_file_hash, itr)
2537
2538     if (options.debug && dynamic_tokens_found)
2539     {
2540       Error(ERR_RETURN_LINE, "-");
2541       Error(ERR_RETURN, "dynamic token(s) found in config file:");
2542       Error(ERR_RETURN, "- config file: '%s'", filename);
2543
2544       for (list = setup_file_list; list != NULL; list = list->next)
2545       {
2546         char *value = getHashEntry(extra_file_hash, list->token);
2547
2548         if (value != NULL && strEqual(value, known_token_value))
2549           Error(ERR_RETURN, "- dynamic token: '%s'", list->token);
2550       }
2551
2552       Error(ERR_RETURN_LINE, "-");
2553     }
2554
2555     if (unknown_tokens_found)
2556     {
2557       Error(ERR_RETURN_LINE, "-");
2558       Error(ERR_RETURN, "warning: unknown token(s) found in config file:");
2559       Error(ERR_RETURN, "- config file: '%s'", filename);
2560
2561       for (list = setup_file_list; list != NULL; list = list->next)
2562       {
2563         char *value = getHashEntry(extra_file_hash, list->token);
2564
2565         if (value != NULL && !strEqual(value, known_token_value))
2566           Error(ERR_RETURN, "- dynamic token: '%s'", list->token);
2567       }
2568
2569       Error(ERR_RETURN_LINE, "-");
2570     }
2571
2572     if (undefined_values_found)
2573     {
2574       Error(ERR_RETURN_LINE, "-");
2575       Error(ERR_RETURN, "warning: undefined values found in config file:");
2576       Error(ERR_RETURN, "- config file: '%s'", filename);
2577
2578       for (list = setup_file_list; list != NULL; list = list->next)
2579       {
2580         char *value = getHashEntry(empty_file_hash, list->token);
2581
2582         if (value != NULL)
2583           Error(ERR_RETURN, "- undefined value for token: '%s'", list->token);
2584       }
2585
2586       Error(ERR_RETURN_LINE, "-");
2587     }
2588
2589     freeSetupFileList(setup_file_list);
2590   }
2591
2592   freeSetupFileHash(extra_file_hash);
2593   freeSetupFileHash(empty_file_hash);
2594
2595 #if 0
2596   for (i = 0; i < num_file_list_entries; i++)
2597   {
2598     printf("'%s' ", file_list[i].token);
2599     if (file_list[i].filename)
2600       printf("-> '%s'\n", file_list[i].filename);
2601     else
2602       printf("-> UNDEFINED [-> '%s']\n", file_list[i].default_filename);
2603   }
2604 #endif
2605 }
2606
2607 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
2608 {
2609   struct FileInfo *file_list = artwork_info->file_list;
2610   int num_file_list_entries = artwork_info->num_file_list_entries;
2611   int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
2612   char *filename_base = UNDEFINED_FILENAME, *filename_local;
2613   int i, j;
2614
2615   DrawInitText("Loading artwork config:", 120, FC_GREEN);
2616   DrawInitText(ARTWORKINFO_FILENAME(artwork_info->type), 150, FC_YELLOW);
2617
2618   /* always start with reliable default values */
2619   for (i = 0; i < num_file_list_entries; i++)
2620   {
2621     setString(&file_list[i].filename, file_list[i].default_filename);
2622
2623     for (j = 0; j < num_suffix_list_entries; j++)
2624       setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
2625
2626     file_list[i].redefined = FALSE;
2627     file_list[i].fallback_to_default = FALSE;
2628   }
2629
2630   /* free previous dynamic artwork file array */
2631   if (artwork_info->dynamic_file_list != NULL)
2632   {
2633     for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
2634     {
2635       free(artwork_info->dynamic_file_list[i].token);
2636       free(artwork_info->dynamic_file_list[i].filename);
2637       free(artwork_info->dynamic_file_list[i].parameter);
2638     }
2639
2640     free(artwork_info->dynamic_file_list);
2641     artwork_info->dynamic_file_list = NULL;
2642
2643     FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
2644                           &artwork_info->num_dynamic_file_list_entries);
2645   }
2646
2647   /* free previous property mapping */
2648   if (artwork_info->property_mapping != NULL)
2649   {
2650     free(artwork_info->property_mapping);
2651
2652     artwork_info->property_mapping = NULL;
2653     artwork_info->num_property_mapping_entries = 0;
2654   }
2655
2656   if (!SETUP_OVERRIDE_ARTWORK(setup, artwork_info->type))
2657   {
2658     /* first look for special artwork configured in level series config */
2659     filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
2660
2661     if (fileExists(filename_base))
2662       LoadArtworkConfigFromFilename(artwork_info, filename_base);
2663   }
2664
2665   filename_local = getCustomArtworkConfigFilename(artwork_info->type);
2666
2667   if (filename_local != NULL && !strEqual(filename_base, filename_local))
2668     LoadArtworkConfigFromFilename(artwork_info, filename_local);
2669 }
2670
2671 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
2672                                    struct ListNodeInfo **listnode)
2673 {
2674   if (*listnode)
2675   {
2676     char *filename = (*listnode)->source_filename;
2677
2678     if (--(*listnode)->num_references <= 0)
2679       deleteNodeFromList(&artwork_info->content_list, filename,
2680                          artwork_info->free_artwork);
2681
2682     *listnode = NULL;
2683   }
2684 }
2685
2686 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
2687                                     struct ListNodeInfo **listnode,
2688                                     struct FileInfo *file_list_entry)
2689 {
2690   char *init_text[] =
2691   {
2692     "Loading graphics:",
2693     "Loading sounds:",
2694     "Loading music:"
2695   };
2696
2697   ListNode *node;
2698   char *basename = file_list_entry->filename;
2699   char *filename = getCustomArtworkFilename(basename, artwork_info->type);
2700
2701   if (filename == NULL)
2702   {
2703     Error(ERR_WARN, "cannot find artwork file '%s'", basename);
2704
2705     basename = file_list_entry->default_filename;
2706
2707     /* dynamic artwork has no default filename / skip empty default artwork */
2708     if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
2709       return;
2710
2711     file_list_entry->fallback_to_default = TRUE;
2712
2713     Error(ERR_WARN, "trying default artwork file '%s'", basename);
2714
2715     filename = getCustomArtworkFilename(basename, artwork_info->type);
2716
2717     if (filename == NULL)
2718     {
2719       int error_mode = ERR_WARN;
2720
2721       /* we can get away without sounds and music, but not without graphics */
2722       if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
2723         error_mode = ERR_EXIT;
2724
2725       Error(error_mode, "cannot find default artwork file '%s'", basename);
2726
2727       return;
2728     }
2729   }
2730
2731   /* check if the old and the new artwork file are the same */
2732   if (*listnode && strEqual((*listnode)->source_filename, filename))
2733   {
2734     /* The old and new artwork are the same (have the same filename and path).
2735        This usually means that this artwork does not exist in this artwork set
2736        and a fallback to the existing artwork is done. */
2737
2738 #if 0
2739     printf("[artwork '%s' already exists (same list entry)]\n", filename);
2740 #endif
2741
2742     return;
2743   }
2744
2745   /* delete existing artwork file entry */
2746   deleteArtworkListEntry(artwork_info, listnode);
2747
2748   /* check if the new artwork file already exists in the list of artworks */
2749   if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
2750   {
2751 #if 0
2752       printf("[artwork '%s' already exists (other list entry)]\n", filename);
2753 #endif
2754
2755       *listnode = (struct ListNodeInfo *)node->content;
2756       (*listnode)->num_references++;
2757
2758       return;
2759   }
2760
2761   DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
2762   DrawInitText(basename, 150, FC_YELLOW);
2763
2764   if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
2765   {
2766 #if 0
2767       printf("[adding new artwork '%s']\n", filename);
2768 #endif
2769
2770     (*listnode)->num_references = 1;
2771     addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
2772                   *listnode);
2773   }
2774   else
2775   {
2776     int error_mode = ERR_WARN;
2777
2778     /* we can get away without sounds and music, but not without graphics */
2779     if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
2780       error_mode = ERR_EXIT;
2781
2782     Error(error_mode, "cannot load artwork file '%s'", basename);
2783     return;
2784   }
2785 }
2786
2787 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
2788                               struct ListNodeInfo **listnode,
2789                               struct FileInfo *file_list_entry)
2790 {
2791 #if 0
2792   printf("GOT CUSTOM ARTWORK FILE '%s'\n", filename);
2793 #endif
2794
2795   if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
2796   {
2797     deleteArtworkListEntry(artwork_info, listnode);
2798     return;
2799   }
2800
2801   replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
2802 }
2803
2804 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
2805 {
2806   struct FileInfo *file_list = artwork_info->file_list;
2807   struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
2808   int num_file_list_entries = artwork_info->num_file_list_entries;
2809   int num_dynamic_file_list_entries =
2810     artwork_info->num_dynamic_file_list_entries;
2811   int i;
2812
2813   for (i = 0; i < num_file_list_entries; i++)
2814     LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
2815                       &file_list[i]);
2816
2817   for (i = 0; i < num_dynamic_file_list_entries; i++)
2818     LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
2819                       &dynamic_file_list[i]);
2820
2821 #if 0
2822   dumpList(artwork_info->content_list);
2823 #endif
2824 }
2825
2826 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
2827                                   struct ListNodeInfo ***list,
2828                                   int *num_list_entries)
2829 {
2830   int i;
2831
2832   if (*list == NULL)
2833     return;
2834
2835   for (i = 0; i < *num_list_entries; i++)
2836     deleteArtworkListEntry(artwork_info, &(*list)[i]);
2837   free(*list);
2838
2839   *list = NULL;
2840   *num_list_entries = 0;
2841 }
2842
2843 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
2844 {
2845   if (artwork_info == NULL)
2846     return;
2847
2848   FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
2849                         &artwork_info->num_file_list_entries);
2850
2851   FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
2852                         &artwork_info->num_dynamic_file_list_entries);
2853 }
2854
2855
2856 /* ------------------------------------------------------------------------- */
2857 /* functions only needed for non-Unix (non-command-line) systems             */
2858 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt")    */
2859 /* (now also added for Windows, to create files in user data directory)      */
2860 /* ------------------------------------------------------------------------- */
2861
2862 char *getErrorFilename(char *basename)
2863 {
2864   return getPath2(getUserDataDir(), basename);
2865 }
2866
2867 void initErrorFile()
2868 {
2869   unlink(program.error_filename);
2870 }
2871
2872 FILE *openErrorFile()
2873 {
2874   FILE *error_file = stderr;
2875
2876 #if defined(PLATFORM_WIN32) || defined(PLATFORM_MSDOS)
2877   if ((error_file = fopen(program.error_filename, MODE_APPEND)) == NULL)
2878     fprintf_newline(stderr, "ERROR: cannot open file '%s' for appending!",
2879                     program.error_filename);
2880 #endif
2881
2882   return error_file;
2883 }
2884
2885 void dumpErrorFile()
2886 {
2887   FILE *error_file = fopen(program.error_filename, MODE_READ);
2888
2889   if (error_file != NULL)
2890   {
2891     while (!feof(error_file))
2892       fputc(fgetc(error_file), stderr);
2893
2894     fclose(error_file);
2895   }
2896 }
2897
2898 void NotifyUserAboutErrorFile()
2899 {
2900 #if defined(PLATFORM_WIN32)
2901   char *title_text = getStringCat2(program.program_title, " Error Message");
2902   char *error_text = getStringCat2("The program was aborted due to an error; "
2903                                    "for details, see the following error file:"
2904                                    STRING_NEWLINE, program.error_filename);
2905
2906   MessageBox(NULL, error_text, title_text, MB_OK);
2907 #endif
2908 }
2909
2910
2911 /* ------------------------------------------------------------------------- */
2912 /* the following is only for debugging purpose and normally not used         */
2913 /* ------------------------------------------------------------------------- */
2914
2915 #define DEBUG_NUM_TIMESTAMPS    3
2916
2917 void debug_print_timestamp(int counter_nr, char *message)
2918 {
2919   static long counter[DEBUG_NUM_TIMESTAMPS][2];
2920
2921   if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
2922     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
2923
2924   counter[counter_nr][0] = Counter();
2925
2926   if (message)
2927     printf("%s %.2f seconds\n", message,
2928            (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
2929
2930   counter[counter_nr][1] = Counter();
2931 }
2932
2933 void debug_print_parent_only(char *format, ...)
2934 {
2935   if (!IS_PARENT_PROCESS())
2936     return;
2937
2938   if (format)
2939   {
2940     va_list ap;
2941
2942     va_start(ap, format);
2943     vprintf(format, ap);
2944     va_end(ap);
2945
2946     printf("\n");
2947   }
2948 }