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