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