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