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