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