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