rnd-20021130-2-src
[rocksndiamonds.git] / src / libgame / misc.c
1 /***********************************************************
2 * Artsoft Retro-Game Library                               *
3 *----------------------------------------------------------*
4 * (c) 1994-2002 Artsoft Entertainment                      *
5 *               Holger Schemel                             *
6 *               Detmolder Strasse 189                      *
7 *               33604 Bielefeld                            *
8 *               Germany                                    *
9 *               e-mail: info@artsoft.org                   *
10 *----------------------------------------------------------*
11 * misc.c                                                   *
12 ***********************************************************/
13
14 #include <time.h>
15 #include <sys/time.h>
16 #include <sys/types.h>
17 #include <stdarg.h>
18 #include <ctype.h>
19 #include <string.h>
20 #include <unistd.h>
21
22 #include "platform.h"
23
24 #if !defined(PLATFORM_WIN32)
25 #include <pwd.h>
26 #include <sys/param.h>
27 #endif
28
29 #include "misc.h"
30 #include "setup.h"
31 #include "random.h"
32 #include "text.h"
33
34
35 #if defined(PLATFORM_MSDOS)
36 volatile unsigned long counter = 0;
37
38 void increment_counter()
39 {
40   counter++;
41 }
42
43 END_OF_FUNCTION(increment_counter);
44 #endif
45
46
47 /* maximal allowed length of a command line option */
48 #define MAX_OPTION_LEN          256
49
50 #ifdef TARGET_SDL
51 static unsigned long mainCounter(int mode)
52 {
53   static unsigned long base_ms = 0;
54   unsigned long current_ms;
55   unsigned long counter_ms;
56
57   current_ms = SDL_GetTicks();
58
59   /* reset base time in case of counter initializing or wrap-around */
60   if (mode == INIT_COUNTER || current_ms < base_ms)
61     base_ms = current_ms;
62
63   counter_ms = current_ms - base_ms;
64
65   return counter_ms;            /* return milliseconds since last init */
66 }
67
68 #else /* !TARGET_SDL */
69
70 #if defined(PLATFORM_UNIX)
71 static unsigned long mainCounter(int mode)
72 {
73   static struct timeval base_time = { 0, 0 };
74   struct timeval current_time;
75   unsigned long counter_ms;
76
77   gettimeofday(&current_time, NULL);
78
79   /* reset base time in case of counter initializing or wrap-around */
80   if (mode == INIT_COUNTER || current_time.tv_sec < base_time.tv_sec)
81     base_time = current_time;
82
83   counter_ms = (current_time.tv_sec  - base_time.tv_sec)  * 1000
84              + (current_time.tv_usec - base_time.tv_usec) / 1000;
85
86   return counter_ms;            /* return milliseconds since last init */
87 }
88 #endif /* PLATFORM_UNIX */
89 #endif /* !TARGET_SDL */
90
91 void InitCounter()              /* set counter back to zero */
92 {
93 #if !defined(PLATFORM_MSDOS)
94   mainCounter(INIT_COUNTER);
95 #else
96   LOCK_VARIABLE(counter);
97   LOCK_FUNCTION(increment_counter);
98   install_int_ex(increment_counter, BPS_TO_TIMER(100));
99 #endif
100 }
101
102 unsigned long Counter() /* get milliseconds since last call of InitCounter() */
103 {
104 #if !defined(PLATFORM_MSDOS)
105   return mainCounter(READ_COUNTER);
106 #else
107   return (counter * 10);
108 #endif
109 }
110
111 static void sleep_milliseconds(unsigned long milliseconds_delay)
112 {
113   boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
114
115 #if 0
116 #if defined(PLATFORM_MSDOS)
117   /* don't use select() to perform waiting operations under DOS
118      environment; always use a busy loop for waiting instead */
119   do_busy_waiting = TRUE;
120 #endif
121 #endif
122
123   if (do_busy_waiting)
124   {
125     /* we want to wait only a few ms -- if we assume that we have a
126        kernel timer resolution of 10 ms, we would wait far to long;
127        therefore it's better to do a short interval of busy waiting
128        to get our sleeping time more accurate */
129
130     unsigned long base_counter = Counter(), actual_counter = Counter();
131
132     while (actual_counter < base_counter + milliseconds_delay &&
133            actual_counter >= base_counter)
134       actual_counter = Counter();
135   }
136   else
137   {
138 #if defined(TARGET_SDL)
139     SDL_Delay(milliseconds_delay);
140 #elif defined(TARGET_ALLEGRO)
141     rest(milliseconds_delay);
142 #else
143     struct timeval delay;
144
145     delay.tv_sec  = milliseconds_delay / 1000;
146     delay.tv_usec = 1000 * (milliseconds_delay % 1000);
147
148     if (select(0, NULL, NULL, NULL, &delay) != 0)
149       Error(ERR_WARN, "sleep_milliseconds(): select() failed");
150 #endif
151   }
152 }
153
154 void Delay(unsigned long delay) /* Sleep specified number of milliseconds */
155 {
156   sleep_milliseconds(delay);
157 }
158
159 boolean FrameReached(unsigned long *frame_counter_var,
160                      unsigned long frame_delay)
161 {
162   unsigned long actual_frame_counter = FrameCounter;
163
164   if (actual_frame_counter < *frame_counter_var + frame_delay &&
165       actual_frame_counter >= *frame_counter_var)
166     return FALSE;
167
168   *frame_counter_var = actual_frame_counter;
169
170   return TRUE;
171 }
172
173 boolean DelayReached(unsigned long *counter_var,
174                      unsigned long delay)
175 {
176   unsigned long actual_counter = Counter();
177
178   if (actual_counter < *counter_var + delay &&
179       actual_counter >= *counter_var)
180     return FALSE;
181
182   *counter_var = actual_counter;
183
184   return TRUE;
185 }
186
187 void WaitUntilDelayReached(unsigned long *counter_var, unsigned long delay)
188 {
189   unsigned long actual_counter;
190
191   while(1)
192   {
193     actual_counter = Counter();
194
195     if (actual_counter < *counter_var + delay &&
196         actual_counter >= *counter_var)
197       sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
198     else
199       break;
200   }
201
202   *counter_var = actual_counter;
203 }
204
205 /* int2str() returns a number converted to a string;
206    the used memory is static, but will be overwritten by later calls,
207    so if you want to save the result, copy it to a private string buffer;
208    there can be 10 local calls of int2str() without buffering the result --
209    the 11th call will then destroy the result from the first call and so on.
210 */
211
212 char *int2str(int number, int size)
213 {
214   static char shift_array[10][40];
215   static int shift_counter = 0;
216   char *s = shift_array[shift_counter];
217
218   shift_counter = (shift_counter + 1) % 10;
219
220   if (size > 20)
221     size = 20;
222
223   if (size)
224   {
225     sprintf(s, "                    %09d", number);
226     return &s[strlen(s) - size];
227   }
228   else
229   {
230     sprintf(s, "%d", number);
231     return s;
232   }
233 }
234
235 unsigned int SimpleRND(unsigned int max)
236 {
237 #if defined(TARGET_SDL)
238   static unsigned long root = 654321;
239   unsigned long current_ms;
240
241   current_ms = SDL_GetTicks();
242   root = root * 4253261 + current_ms;
243   return (root % max);
244 #else
245   static unsigned long root = 654321;
246   struct timeval current_time;
247
248   gettimeofday(&current_time, NULL);
249   root = root * 4253261 + current_time.tv_sec + current_time.tv_usec;
250   return (root % max);
251 #endif
252 }
253
254 #ifdef DEBUG
255 static unsigned int last_RND_value = 0;
256
257 unsigned int last_RND()
258 {
259   return last_RND_value;
260 }
261 #endif
262
263 unsigned int RND(unsigned int max)
264 {
265 #ifdef DEBUG
266   return (last_RND_value = random_linux_libc() % max);
267 #else
268   return (random_linux_libc() % max);
269 #endif
270 }
271
272 unsigned int InitRND(long seed)
273 {
274 #if defined(TARGET_SDL)
275   unsigned long current_ms;
276
277   if (seed == NEW_RANDOMIZE)
278   {
279     current_ms = SDL_GetTicks();
280     srandom_linux_libc((unsigned int) current_ms);
281     return (unsigned int) current_ms;
282   }
283   else
284   {
285     srandom_linux_libc((unsigned int) seed);
286     return (unsigned int) seed;
287   }
288 #else
289   struct timeval current_time;
290
291   if (seed == NEW_RANDOMIZE)
292   {
293     gettimeofday(&current_time, NULL);
294     srandom_linux_libc((unsigned int) current_time.tv_usec);
295     return (unsigned int) current_time.tv_usec;
296   }
297   else
298   {
299     srandom_linux_libc((unsigned int) seed);
300     return (unsigned int) seed;
301   }
302 #endif
303 }
304
305 char *getLoginName()
306 {
307 #if defined(PLATFORM_WIN32)
308   return ANONYMOUS_NAME;
309 #else
310   static char *login_name = NULL;
311
312   if (login_name == NULL)
313   {
314     struct passwd *pwd;
315
316     if ((pwd = getpwuid(getuid())) == NULL)
317       login_name = ANONYMOUS_NAME;
318     else
319       login_name = getStringCopy(pwd->pw_name);
320   }
321
322   return login_name;
323 #endif
324 }
325
326 char *getRealName()
327 {
328 #if defined(PLATFORM_UNIX)
329   struct passwd *pwd;
330
331   if ((pwd = getpwuid(getuid())) == NULL || strlen(pwd->pw_gecos) == 0)
332     return ANONYMOUS_NAME;
333   else
334   {
335     static char real_name[1024];
336     char *from_ptr = pwd->pw_gecos, *to_ptr = real_name;
337
338     if (strchr(pwd->pw_gecos, 'ß') == NULL)
339       return pwd->pw_gecos;
340
341     /* the user's real name contains a 'ß' character (german sharp s),
342        which has no equivalent in upper case letters (which our fonts use) */
343     while (*from_ptr != '\0' && (long)(to_ptr - real_name) < 1024 - 2)
344     {
345       if (*from_ptr != 'ß')
346         *to_ptr++ = *from_ptr++;
347       else
348       {
349         from_ptr++;
350         *to_ptr++ = 's';
351         *to_ptr++ = 's';
352       }
353     }
354     *to_ptr = '\0';
355
356     return real_name;
357   }
358 #else /* !PLATFORM_UNIX */
359   return ANONYMOUS_NAME;
360 #endif
361 }
362
363 char *getHomeDir()
364 {
365 #if defined(PLATFORM_UNIX)
366   static char *home_dir = NULL;
367
368   if (home_dir == NULL)
369   {
370     if ((home_dir = getenv("HOME")) == NULL)
371     {
372       struct passwd *pwd;
373
374       if ((pwd = getpwuid(getuid())) == NULL)
375         home_dir = ".";
376       else
377         home_dir = getStringCopy(pwd->pw_dir);
378     }
379   }
380
381   return home_dir;
382 #else
383   return ".";
384 #endif
385 }
386
387 char *getPath2(char *path1, char *path2)
388 {
389   char *complete_path = checked_malloc(strlen(path1) + 1 +
390                                        strlen(path2) + 1);
391
392   sprintf(complete_path, "%s/%s", path1, path2);
393   return complete_path;
394 }
395
396 char *getPath3(char *path1, char *path2, char *path3)
397 {
398   char *complete_path = checked_malloc(strlen(path1) + 1 +
399                                        strlen(path2) + 1 +
400                                        strlen(path3) + 1);
401
402   sprintf(complete_path, "%s/%s/%s", path1, path2, path3);
403   return complete_path;
404 }
405
406 static char *getStringCat2(char *s1, char *s2)
407 {
408   char *complete_string = checked_malloc(strlen(s1) + strlen(s2) + 1);
409
410   sprintf(complete_string, "%s%s", s1, s2);
411   return complete_string;
412 }
413
414 char *getStringCopy(char *s)
415 {
416   char *s_copy;
417
418   if (s == NULL)
419     return NULL;
420
421   s_copy = checked_malloc(strlen(s) + 1);
422
423   strcpy(s_copy, s);
424   return s_copy;
425 }
426
427 char *getStringToLower(char *s)
428 {
429   char *s_copy = checked_malloc(strlen(s) + 1);
430   char *s_ptr = s_copy;
431
432   while (*s)
433     *s_ptr++ = tolower(*s++);
434   *s_ptr = '\0';
435
436   return s_copy;
437 }
438
439 void GetOptions(char *argv[])
440 {
441   char **options_left = &argv[1];
442
443   /* initialize global program options */
444   options.display_name = NULL;
445   options.server_host = NULL;
446   options.server_port = 0;
447   options.ro_base_directory = RO_BASE_PATH;
448   options.rw_base_directory = RW_BASE_PATH;
449   options.level_directory = RO_BASE_PATH "/" LEVELS_DIRECTORY;
450   options.graphics_directory = RO_BASE_PATH "/" GRAPHICS_DIRECTORY;
451   options.sounds_directory = RO_BASE_PATH "/" SOUNDS_DIRECTORY;
452   options.music_directory = RO_BASE_PATH "/" MUSIC_DIRECTORY;
453   options.serveronly = FALSE;
454   options.network = FALSE;
455   options.verbose = FALSE;
456   options.debug = FALSE;
457   options.debug_command = NULL;
458
459   while (*options_left)
460   {
461     char option_str[MAX_OPTION_LEN];
462     char *option = options_left[0];
463     char *next_option = options_left[1];
464     char *option_arg = NULL;
465     int option_len = strlen(option);
466
467     if (option_len >= MAX_OPTION_LEN)
468       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
469
470     strcpy(option_str, option);                 /* copy argument into buffer */
471     option = option_str;
472
473     if (strcmp(option, "--") == 0)              /* stop scanning arguments */
474       break;
475
476     if (strncmp(option, "--", 2) == 0)          /* treat '--' like '-' */
477       option++;
478
479     option_arg = strchr(option, '=');
480     if (option_arg == NULL)                     /* no '=' in option */
481       option_arg = next_option;
482     else
483     {
484       *option_arg++ = '\0';                     /* cut argument from option */
485       if (*option_arg == '\0')                  /* no argument after '=' */
486         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
487     }
488
489     option_len = strlen(option);
490
491     if (strcmp(option, "-") == 0)
492       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
493     else if (strncmp(option, "-help", option_len) == 0)
494     {
495       printf("Usage: %s [options] [<server host> [<server port>]]\n"
496              "Options:\n"
497              "  -d, --display <host>[:<scr>]  X server display\n"
498              "  -b, --basepath <directory>    alternative base directory\n"
499              "  -l, --level <directory>       alternative level directory\n"
500              "  -g, --graphics <directory>    alternative graphics directory\n"
501              "  -s, --sounds <directory>      alternative sounds directory\n"
502              "  -m, --music <directory>       alternative music directory\n"
503              "  -n, --network                 network multiplayer game\n"
504              "      --serveronly              only start network server\n"
505              "  -v, --verbose                 verbose mode\n"
506              "      --debug                   display debugging information\n",
507              program.command_basename);
508
509       if (options.debug)
510         printf("      --debug-command <command> execute special command\n");
511
512       exit(0);
513     }
514     else if (strncmp(option, "-display", option_len) == 0)
515     {
516       if (option_arg == NULL)
517         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
518
519       options.display_name = option_arg;
520       if (option_arg == next_option)
521         options_left++;
522     }
523     else if (strncmp(option, "-basepath", option_len) == 0)
524     {
525       if (option_arg == NULL)
526         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
527
528       /* this should be extended to separate options for ro and rw data */
529       options.ro_base_directory = option_arg;
530       options.rw_base_directory = option_arg;
531       if (option_arg == next_option)
532         options_left++;
533
534       /* adjust path for level directory accordingly */
535       options.level_directory =
536         getPath2(options.ro_base_directory, LEVELS_DIRECTORY);
537     }
538     else if (strncmp(option, "-levels", option_len) == 0)
539     {
540       if (option_arg == NULL)
541         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
542
543       options.level_directory = option_arg;
544       if (option_arg == next_option)
545         options_left++;
546     }
547     else if (strncmp(option, "-graphics", option_len) == 0)
548     {
549       if (option_arg == NULL)
550         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
551
552       options.graphics_directory = option_arg;
553       if (option_arg == next_option)
554         options_left++;
555     }
556     else if (strncmp(option, "-sounds", option_len) == 0)
557     {
558       if (option_arg == NULL)
559         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
560
561       options.sounds_directory = option_arg;
562       if (option_arg == next_option)
563         options_left++;
564     }
565     else if (strncmp(option, "-music", option_len) == 0)
566     {
567       if (option_arg == NULL)
568         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
569
570       options.music_directory = option_arg;
571       if (option_arg == next_option)
572         options_left++;
573     }
574     else if (strncmp(option, "-network", option_len) == 0)
575     {
576       options.network = TRUE;
577     }
578     else if (strncmp(option, "-serveronly", option_len) == 0)
579     {
580       options.serveronly = TRUE;
581     }
582     else if (strncmp(option, "-verbose", option_len) == 0)
583     {
584       options.verbose = TRUE;
585     }
586     else if (strncmp(option, "-debug", option_len) == 0)
587     {
588       options.debug = TRUE;
589     }
590     else if (strncmp(option, "-debug-command", option_len) == 0)
591     {
592       if (option_arg == NULL)
593         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
594
595       options.debug_command = option_arg;
596       if (option_arg == next_option)
597         options_left++;
598     }
599     else if (*option == '-')
600     {
601       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
602     }
603     else if (options.server_host == NULL)
604     {
605       options.server_host = *options_left;
606     }
607     else if (options.server_port == 0)
608     {
609       options.server_port = atoi(*options_left);
610       if (options.server_port < 1024)
611         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
612     }
613     else
614       Error(ERR_EXIT_HELP, "too many arguments");
615
616     options_left++;
617   }
618 }
619
620 /* used by SetError() and GetError() to store internal error messages */
621 static char internal_error[1024];       /* this is bad */
622
623 void SetError(char *format, ...)
624 {
625   va_list ap;
626
627   va_start(ap, format);
628   vsprintf(internal_error, format, ap);
629   va_end(ap);
630 }
631
632 char *GetError()
633 {
634   return internal_error;
635 }
636
637 void Error(int mode, char *format, ...)
638 {
639   char *process_name = "";
640   FILE *error = stderr;
641   char *newline = "\n";
642
643   /* display warnings only when running in verbose mode */
644   if (mode & ERR_WARN && !options.verbose)
645     return;
646
647 #if defined(PLATFORM_MSDOS)
648   newline = "\r\n";
649
650   if ((error = openErrorFile()) == NULL)
651   {
652     printf("Cannot write to error output file!%s", newline);
653     program.exit_function(1);
654   }
655 #endif
656
657   if (mode & ERR_SOUND_SERVER)
658     process_name = " sound server";
659   else if (mode & ERR_NETWORK_SERVER)
660     process_name = " network server";
661   else if (mode & ERR_NETWORK_CLIENT)
662     process_name = " network client **";
663
664   if (format)
665   {
666     va_list ap;
667
668     fprintf(error, "%s%s: ", program.command_basename, process_name);
669
670     if (mode & ERR_WARN)
671       fprintf(error, "warning: ");
672
673     va_start(ap, format);
674     vfprintf(error, format, ap);
675     va_end(ap);
676   
677     fprintf(error, "%s", newline);
678   }
679   
680   if (mode & ERR_HELP)
681     fprintf(error, "%s: Try option '--help' for more information.%s",
682             program.command_basename, newline);
683
684   if (mode & ERR_EXIT)
685     fprintf(error, "%s%s: aborting%s",
686             program.command_basename, process_name, newline);
687
688   if (error != stderr)
689     fclose(error);
690
691   if (mode & ERR_EXIT)
692   {
693     if (mode & ERR_FROM_SERVER)
694       exit(1);                          /* child process: normal exit */
695     else
696       program.exit_function(1);         /* main process: clean up stuff */
697   }
698 }
699
700 void *checked_malloc(unsigned long size)
701 {
702   void *ptr;
703
704   ptr = malloc(size);
705
706   if (ptr == NULL)
707     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
708
709   return ptr;
710 }
711
712 void *checked_calloc(unsigned long size)
713 {
714   void *ptr;
715
716   ptr = calloc(1, size);
717
718   if (ptr == NULL)
719     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
720
721   return ptr;
722 }
723
724 void *checked_realloc(void *ptr, unsigned long size)
725 {
726   ptr = realloc(ptr, size);
727
728   if (ptr == NULL)
729     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
730
731   return ptr;
732 }
733
734 inline void swap_numbers(int *i1, int *i2)
735 {
736   int help = *i1;
737
738   *i1 = *i2;
739   *i2 = help;
740 }
741
742 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
743 {
744   int help_x = *x1;
745   int help_y = *y1;
746
747   *x1 = *x2;
748   *x2 = help_x;
749
750   *y1 = *y2;
751   *y2 = help_y;
752 }
753
754 short getFile16BitInteger(FILE *file, int byte_order)
755 {
756   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
757     return ((fgetc(file) <<  8) |
758             (fgetc(file) <<  0));
759   else           /* BYTE_ORDER_LITTLE_ENDIAN */
760     return ((fgetc(file) <<  0) |
761             (fgetc(file) <<  8));
762 }
763
764 void putFile16BitInteger(FILE *file, short value, int byte_order)
765 {
766   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
767   {
768     fputc((value >>  8) & 0xff, file);
769     fputc((value >>  0) & 0xff, file);
770   }
771   else           /* BYTE_ORDER_LITTLE_ENDIAN */
772   {
773     fputc((value >>  0) & 0xff, file);
774     fputc((value >>  8) & 0xff, file);
775   }
776 }
777
778 int getFile32BitInteger(FILE *file, int byte_order)
779 {
780   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
781     return ((fgetc(file) << 24) |
782             (fgetc(file) << 16) |
783             (fgetc(file) <<  8) |
784             (fgetc(file) <<  0));
785   else           /* BYTE_ORDER_LITTLE_ENDIAN */
786     return ((fgetc(file) <<  0) |
787             (fgetc(file) <<  8) |
788             (fgetc(file) << 16) |
789             (fgetc(file) << 24));
790 }
791
792 void putFile32BitInteger(FILE *file, int value, int byte_order)
793 {
794   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
795   {
796     fputc((value >> 24) & 0xff, file);
797     fputc((value >> 16) & 0xff, file);
798     fputc((value >>  8) & 0xff, file);
799     fputc((value >>  0) & 0xff, file);
800   }
801   else           /* BYTE_ORDER_LITTLE_ENDIAN */
802   {
803     fputc((value >>  0) & 0xff, file);
804     fputc((value >>  8) & 0xff, file);
805     fputc((value >> 16) & 0xff, file);
806     fputc((value >> 24) & 0xff, file);
807   }
808 }
809
810 boolean getFileChunk(FILE *file, char *chunk_name, int *chunk_size,
811                      int byte_order)
812 {
813   const int chunk_name_length = 4;
814
815   /* read chunk name */
816   fgets(chunk_name, chunk_name_length + 1, file);
817
818   if (chunk_size != NULL)
819   {
820     /* read chunk size */
821     *chunk_size = getFile32BitInteger(file, byte_order);
822   }
823
824   return (feof(file) || ferror(file) ? FALSE : TRUE);
825 }
826
827 void putFileChunk(FILE *file, char *chunk_name, int chunk_size,
828                   int byte_order)
829 {
830   /* write chunk name */
831   fputs(chunk_name, file);
832
833   if (chunk_size >= 0)
834   {
835     /* write chunk size */
836     putFile32BitInteger(file, chunk_size, byte_order);
837   }
838 }
839
840 int getFileVersion(FILE *file)
841 {
842   int version_major, version_minor, version_patch;
843
844   version_major = fgetc(file);
845   version_minor = fgetc(file);
846   version_patch = fgetc(file);
847   fgetc(file);          /* not used */
848
849   return VERSION_IDENT(version_major, version_minor, version_patch);
850 }
851
852 void putFileVersion(FILE *file, int version)
853 {
854   int version_major = VERSION_MAJOR(version);
855   int version_minor = VERSION_MINOR(version);
856   int version_patch = VERSION_PATCH(version);
857
858   fputc(version_major, file);
859   fputc(version_minor, file);
860   fputc(version_patch, file);
861   fputc(0, file);       /* not used */
862 }
863
864 void ReadUnusedBytesFromFile(FILE *file, unsigned long bytes)
865 {
866   while (bytes-- && !feof(file))
867     fgetc(file);
868 }
869
870 void WriteUnusedBytesToFile(FILE *file, unsigned long bytes)
871 {
872   while (bytes--)
873     fputc(0, file);
874 }
875
876
877 /* ------------------------------------------------------------------------- */
878 /* functions to translate key identifiers between different format           */
879 /* ------------------------------------------------------------------------- */
880
881 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
882 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
883 #define TRANSLATE_KEYNAME_TO_KEYSYM     2
884 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  3
885
886 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
887 {
888   static struct
889   {
890     Key key;
891     char *x11name;
892     char *name;
893   } translate_key[] =
894   {
895     /* normal cursor keys */
896     { KSYM_Left,        "XK_Left",              "cursor left" },
897     { KSYM_Right,       "XK_Right",             "cursor right" },
898     { KSYM_Up,          "XK_Up",                "cursor up" },
899     { KSYM_Down,        "XK_Down",              "cursor down" },
900
901     /* keypad cursor keys */
902 #ifdef KSYM_KP_Left
903     { KSYM_KP_Left,     "XK_KP_Left",           "keypad left" },
904     { KSYM_KP_Right,    "XK_KP_Right",          "keypad right" },
905     { KSYM_KP_Up,       "XK_KP_Up",             "keypad up" },
906     { KSYM_KP_Down,     "XK_KP_Down",           "keypad down" },
907 #endif
908
909     /* other keypad keys */
910 #ifdef KSYM_KP_Enter
911     { KSYM_KP_Enter,    "XK_KP_Enter",          "keypad enter" },
912     { KSYM_KP_Add,      "XK_KP_Add",            "keypad +" },
913     { KSYM_KP_Subtract, "XK_KP_Subtract",       "keypad -" },
914     { KSYM_KP_Multiply, "XK_KP_Multiply",       "keypad mltply" },
915     { KSYM_KP_Divide,   "XK_KP_Divide",         "keypad /" },
916     { KSYM_KP_Separator,"XK_KP_Separator",      "keypad ," },
917 #endif
918
919     /* modifier keys */
920     { KSYM_Shift_L,     "XK_Shift_L",           "left shift" },
921     { KSYM_Shift_R,     "XK_Shift_R",           "right shift" },
922     { KSYM_Control_L,   "XK_Control_L",         "left control" },
923     { KSYM_Control_R,   "XK_Control_R",         "right control" },
924     { KSYM_Meta_L,      "XK_Meta_L",            "left meta" },
925     { KSYM_Meta_R,      "XK_Meta_R",            "right meta" },
926     { KSYM_Alt_L,       "XK_Alt_L",             "left alt" },
927     { KSYM_Alt_R,       "XK_Alt_R",             "right alt" },
928     { KSYM_Super_L,     "XK_Super_L",           "left super" },  /* Win-L */
929     { KSYM_Super_R,     "XK_Super_R",           "right super" }, /* Win-R */
930     { KSYM_Mode_switch, "XK_Mode_switch",       "mode switch" }, /* Alt-R */
931     { KSYM_Multi_key,   "XK_Multi_key",         "multi key" },   /* Ctrl-R */
932
933     /* some special keys */
934     { KSYM_BackSpace,   "XK_BackSpace",         "backspace" },
935     { KSYM_Delete,      "XK_Delete",            "delete" },
936     { KSYM_Insert,      "XK_Insert",            "insert" },
937     { KSYM_Tab,         "XK_Tab",               "tab" },
938     { KSYM_Home,        "XK_Home",              "home" },
939     { KSYM_End,         "XK_End",               "end" },
940     { KSYM_Page_Up,     "XK_Page_Up",           "page up" },
941     { KSYM_Page_Down,   "XK_Page_Down",         "page down" },
942     { KSYM_Menu,        "XK_Menu",              "menu" },        /* Win-Menu */
943
944     /* ASCII 0x20 to 0x40 keys (except numbers) */
945     { KSYM_space,       "XK_space",             "space" },
946     { KSYM_exclam,      "XK_exclam",            "!" },
947     { KSYM_quotedbl,    "XK_quotedbl",          "\"" },
948     { KSYM_numbersign,  "XK_numbersign",        "#" },
949     { KSYM_dollar,      "XK_dollar",            "$" },
950     { KSYM_percent,     "XK_percent",           "%" },
951     { KSYM_ampersand,   "XK_ampersand",         "&" },
952     { KSYM_apostrophe,  "XK_apostrophe",        "'" },
953     { KSYM_parenleft,   "XK_parenleft",         "(" },
954     { KSYM_parenright,  "XK_parenright",        ")" },
955     { KSYM_asterisk,    "XK_asterisk",          "*" },
956     { KSYM_plus,        "XK_plus",              "+" },
957     { KSYM_comma,       "XK_comma",             "," },
958     { KSYM_minus,       "XK_minus",             "-" },
959     { KSYM_period,      "XK_period",            "." },
960     { KSYM_slash,       "XK_slash",             "/" },
961     { KSYM_colon,       "XK_colon",             ":" },
962     { KSYM_semicolon,   "XK_semicolon",         ";" },
963     { KSYM_less,        "XK_less",              "<" },
964     { KSYM_equal,       "XK_equal",             "=" },
965     { KSYM_greater,     "XK_greater",           ">" },
966     { KSYM_question,    "XK_question",          "?" },
967     { KSYM_at,          "XK_at",                "@" },
968
969     /* more ASCII keys */
970     { KSYM_bracketleft, "XK_bracketleft",       "[" },
971     { KSYM_backslash,   "XK_backslash",         "backslash" },
972     { KSYM_bracketright,"XK_bracketright",      "]" },
973     { KSYM_asciicircum, "XK_asciicircum",       "circumflex" },
974     { KSYM_underscore,  "XK_underscore",        "_" },
975     { KSYM_grave,       "XK_grave",             "grave" },
976     { KSYM_quoteleft,   "XK_quoteleft",         "quote left" },
977     { KSYM_braceleft,   "XK_braceleft",         "brace left" },
978     { KSYM_bar,         "XK_bar",               "bar" },
979     { KSYM_braceright,  "XK_braceright",        "brace right" },
980     { KSYM_asciitilde,  "XK_asciitilde",        "ascii tilde" },
981
982     /* special (non-ASCII) keys */
983     { KSYM_Adiaeresis,  "XK_Adiaeresis",        "Ä" },
984     { KSYM_Odiaeresis,  "XK_Odiaeresis",        "Ö" },
985     { KSYM_Udiaeresis,  "XK_Udiaeresis",        "Ãœ" },
986     { KSYM_adiaeresis,  "XK_adiaeresis",        "ä" },
987     { KSYM_odiaeresis,  "XK_odiaeresis",        "ö" },
988     { KSYM_udiaeresis,  "XK_udiaeresis",        "ü" },
989     { KSYM_ssharp,      "XK_ssharp",            "sharp s" },
990
991     /* end-of-array identifier */
992     { 0,                NULL,                   NULL }
993   };
994
995   int i;
996
997   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
998   {
999     static char name_buffer[30];
1000     Key key = *keysym;
1001
1002     if (key >= KSYM_A && key <= KSYM_Z)
1003       sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1004     else if (key >= KSYM_a && key <= KSYM_z)
1005       sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1006     else if (key >= KSYM_0 && key <= KSYM_9)
1007       sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1008     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1009       sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1010     else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1011       sprintf(name_buffer, "function F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1012     else if (key == KSYM_UNDEFINED)
1013       strcpy(name_buffer, "(undefined)");
1014     else
1015     {
1016       i = 0;
1017
1018       do
1019       {
1020         if (key == translate_key[i].key)
1021         {
1022           strcpy(name_buffer, translate_key[i].name);
1023           break;
1024         }
1025       }
1026       while (translate_key[++i].name);
1027
1028       if (!translate_key[i].name)
1029         strcpy(name_buffer, "(unknown)");
1030     }
1031
1032     *name = name_buffer;
1033   }
1034   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1035   {
1036     static char name_buffer[30];
1037     Key key = *keysym;
1038
1039     if (key >= KSYM_A && key <= KSYM_Z)
1040       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1041     else if (key >= KSYM_a && key <= KSYM_z)
1042       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1043     else if (key >= KSYM_0 && key <= KSYM_9)
1044       sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1045     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1046       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1047     else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1048       sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1049     else if (key == KSYM_UNDEFINED)
1050       strcpy(name_buffer, "[undefined]");
1051     else
1052     {
1053       i = 0;
1054
1055       do
1056       {
1057         if (key == translate_key[i].key)
1058         {
1059           strcpy(name_buffer, translate_key[i].x11name);
1060           break;
1061         }
1062       }
1063       while (translate_key[++i].x11name);
1064
1065       if (!translate_key[i].x11name)
1066         sprintf(name_buffer, "0x%04lx", (unsigned long)key);
1067     }
1068
1069     *x11name = name_buffer;
1070   }
1071   else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1072   {
1073     Key key = KSYM_UNDEFINED;
1074
1075     i = 0;
1076     do
1077     {
1078       if (strcmp(translate_key[i].name, *name) == 0)
1079       {
1080         key = translate_key[i].key;
1081         break;
1082       }
1083     }
1084     while (translate_key[++i].x11name);
1085
1086     if (key == KSYM_UNDEFINED)
1087       Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1088
1089     *keysym = key;
1090   }
1091   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1092   {
1093     Key key = KSYM_UNDEFINED;
1094     char *name_ptr = *x11name;
1095
1096     if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
1097     {
1098       char c = name_ptr[3];
1099
1100       if (c >= 'A' && c <= 'Z')
1101         key = KSYM_A + (Key)(c - 'A');
1102       else if (c >= 'a' && c <= 'z')
1103         key = KSYM_a + (Key)(c - 'a');
1104       else if (c >= '0' && c <= '9')
1105         key = KSYM_0 + (Key)(c - '0');
1106     }
1107     else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
1108     {
1109       char c = name_ptr[6];
1110
1111       if (c >= '0' && c <= '9')
1112         key = KSYM_0 + (Key)(c - '0');
1113     }
1114     else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
1115     {
1116       char c1 = name_ptr[4];
1117       char c2 = name_ptr[5];
1118       int d = 0;
1119
1120       if ((c1 >= '0' && c1 <= '9') &&
1121           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1122         d = atoi(&name_ptr[4]);
1123
1124       if (d >= 1 && d <= KSYM_NUM_FKEYS)
1125         key = KSYM_F1 + (Key)(d - 1);
1126     }
1127     else if (strncmp(name_ptr, "XK_", 3) == 0)
1128     {
1129       i = 0;
1130
1131       do
1132       {
1133         if (strcmp(name_ptr, translate_key[i].x11name) == 0)
1134         {
1135           key = translate_key[i].key;
1136           break;
1137         }
1138       }
1139       while (translate_key[++i].x11name);
1140     }
1141     else if (strncmp(name_ptr, "0x", 2) == 0)
1142     {
1143       unsigned long value = 0;
1144
1145       name_ptr += 2;
1146
1147       while (name_ptr)
1148       {
1149         char c = *name_ptr++;
1150         int d = -1;
1151
1152         if (c >= '0' && c <= '9')
1153           d = (int)(c - '0');
1154         else if (c >= 'a' && c <= 'f')
1155           d = (int)(c - 'a' + 10);
1156         else if (c >= 'A' && c <= 'F')
1157           d = (int)(c - 'A' + 10);
1158
1159         if (d == -1)
1160         {
1161           value = -1;
1162           break;
1163         }
1164
1165         value = value * 16 + d;
1166       }
1167
1168       if (value != -1)
1169         key = (Key)value;
1170     }
1171
1172     *keysym = key;
1173   }
1174 }
1175
1176 char *getKeyNameFromKey(Key key)
1177 {
1178   char *name;
1179
1180   translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1181   return name;
1182 }
1183
1184 char *getX11KeyNameFromKey(Key key)
1185 {
1186   char *x11name;
1187
1188   translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1189   return x11name;
1190 }
1191
1192 Key getKeyFromKeyName(char *name)
1193 {
1194   Key key;
1195
1196   translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1197   return key;
1198 }
1199
1200 Key getKeyFromX11KeyName(char *x11name)
1201 {
1202   Key key;
1203
1204   translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1205   return key;
1206 }
1207
1208 char getCharFromKey(Key key)
1209 {
1210   char *keyname = getKeyNameFromKey(key);
1211   char letter = 0;
1212
1213   if (strlen(keyname) == 1)
1214     letter = keyname[0];
1215   else if (strcmp(keyname, "space") == 0)
1216     letter = ' ';
1217   else if (strcmp(keyname, "circumflex") == 0)
1218     letter = '^';
1219
1220   return letter;
1221 }
1222
1223
1224 /* ========================================================================= */
1225 /* functions for generic lists                                               */
1226 /* ========================================================================= */
1227
1228 ListNode *newListNode()
1229 {
1230   return checked_calloc(sizeof(ListNode));
1231 }
1232
1233 void addNodeToList(ListNode **node_first, char *key, void *content)
1234 {
1235   ListNode *node_new = newListNode();
1236
1237 #if 0
1238   printf("LIST: adding node with key '%s'\n", key);
1239 #endif
1240
1241   node_new->key = getStringCopy(key);
1242   node_new->content = content;
1243   node_new->next = *node_first;
1244   *node_first = node_new;
1245 }
1246
1247 void deleteNodeFromList(ListNode **node_first, char *key,
1248                         void (*destructor_function)(void *))
1249 {
1250   if (node_first == NULL || *node_first == NULL)
1251     return;
1252
1253 #if 0
1254   printf("[CHECKING LIST KEY '%s' == '%s']\n",
1255          (*node_first)->key, key);
1256 #endif
1257
1258   if (strcmp((*node_first)->key, key) == 0)
1259   {
1260 #if 0
1261     printf("[DELETING LIST ENTRY]\n");
1262 #endif
1263
1264     free((*node_first)->key);
1265     if (destructor_function)
1266       destructor_function((*node_first)->content);
1267     *node_first = (*node_first)->next;
1268   }
1269   else
1270     deleteNodeFromList(&(*node_first)->next, key, destructor_function);
1271 }
1272
1273 ListNode *getNodeFromKey(ListNode *node_first, char *key)
1274 {
1275   if (node_first == NULL)
1276     return NULL;
1277
1278   if (strcmp(node_first->key, key) == 0)
1279     return node_first;
1280   else
1281     return getNodeFromKey(node_first->next, key);
1282 }
1283
1284 int getNumNodes(ListNode *node_first)
1285 {
1286   return (node_first ? 1 + getNumNodes(node_first->next) : 0);
1287 }
1288
1289 void dumpList(ListNode *node_first)
1290 {
1291   ListNode *node = node_first;
1292
1293   while (node)
1294   {
1295     printf("['%s' (%d)]\n", node->key,
1296            ((struct ListNodeInfo *)node->content)->num_references);
1297     node = node->next;
1298   }
1299
1300   printf("[%d nodes]\n", getNumNodes(node_first));
1301 }
1302
1303
1304 /* ========================================================================= */
1305 /* functions for checking filenames                                          */
1306 /* ========================================================================= */
1307
1308 boolean FileIsGraphic(char *filename)
1309 {
1310   if (strlen(filename) > 4 &&
1311       strcmp(&filename[strlen(filename) - 4], ".pcx") == 0)
1312     return TRUE;
1313
1314   return FALSE;
1315 }
1316
1317 boolean FileIsSound(char *basename)
1318 {
1319   if (strlen(basename) > 4 &&
1320       strcmp(&basename[strlen(basename) - 4], ".wav") == 0)
1321     return TRUE;
1322
1323   return FALSE;
1324 }
1325
1326 boolean FileIsMusic(char *basename)
1327 {
1328   /* "music" can be a WAV (loop) file or (if compiled with SDL) a MOD file */
1329
1330   if (FileIsSound(basename))
1331     return TRUE;
1332
1333 #if defined(TARGET_SDL)
1334   if (strlen(basename) > 4 &&
1335       (strcmp(&basename[strlen(basename) - 4], ".mod") == 0 ||
1336        strcmp(&basename[strlen(basename) - 4], ".MOD") == 0 ||
1337        strncmp(basename, "mod.", 4) == 0 ||
1338        strncmp(basename, "MOD.", 4) == 0))
1339     return TRUE;
1340 #endif
1341
1342   return FALSE;
1343 }
1344
1345 boolean FileIsArtworkType(char *basename, int type)
1346 {
1347   if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(basename)) ||
1348       (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(basename)) ||
1349       (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(basename)))
1350     return TRUE;
1351
1352   return FALSE;
1353 }
1354
1355 /* ========================================================================= */
1356 /* functions for loading artwork configuration information                   */
1357 /* ========================================================================= */
1358
1359 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
1360                                            struct ConfigInfo *suffix_list,
1361                                            int num_file_list_entries)
1362 {
1363   struct FileInfo *file_list;
1364   int num_suffix_list_entries = 0;
1365   int list_pos = 0;
1366   int i, j;
1367
1368   file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
1369
1370   for (i=0; suffix_list[i].token != NULL; i++)
1371     num_suffix_list_entries++;
1372
1373   /* always start with reliable default values */
1374   for (i=0; i<num_file_list_entries; i++)
1375   {
1376     file_list[i].token = NULL;
1377     file_list[i].default_filename = NULL;
1378     file_list[i].filename = NULL;
1379
1380     if (num_suffix_list_entries > 0)
1381     {
1382       int parameter_array_size = num_suffix_list_entries * sizeof(int);
1383
1384       file_list[i].default_parameter = checked_calloc(parameter_array_size);
1385       file_list[i].parameter = checked_calloc(parameter_array_size);
1386
1387       for (j=0; j<num_suffix_list_entries; j++)
1388       {
1389         int default_parameter = atoi(suffix_list[j].value);
1390
1391         file_list[i].default_parameter[j] = default_parameter;
1392         file_list[i].parameter[j] = default_parameter;
1393       }
1394     }
1395   }
1396
1397   for (i=0; config_list[i].token != NULL; i++)
1398   {
1399     int len_config_token = strlen(config_list[i].token);
1400     int len_config_value = strlen(config_list[i].value);
1401     boolean is_file_entry = TRUE;
1402
1403     for (j=0; suffix_list[j].token != NULL; j++)
1404     {
1405       int len_suffix = strlen(suffix_list[j].token);
1406
1407       if (len_suffix < len_config_token &&
1408           strcmp(&config_list[i].token[len_config_token - len_suffix],
1409                  suffix_list[j].token) == 0)
1410       {
1411         file_list[list_pos].default_parameter[j] = atoi(config_list[i].value);
1412
1413         is_file_entry = FALSE;
1414         break;
1415       }
1416     }
1417
1418     if (is_file_entry)
1419     {
1420       if (i > 0)
1421         list_pos++;
1422
1423       if (list_pos > num_file_list_entries - 1)
1424         break;
1425
1426       /* simple sanity check if this is really a file definition */
1427       if (strcmp(&config_list[i].value[len_config_value - 4], ".pcx") != 0 &&
1428           strcmp(&config_list[i].value[len_config_value - 4], ".wav") != 0 &&
1429           strcmp(config_list[i].value, UNDEFINED_FILENAME) != 0)
1430       {
1431         Error(ERR_RETURN, "Configuration directive '%s' -> '%s':",
1432               config_list[i].token, config_list[i].value);
1433         Error(ERR_EXIT, "This seems to be no valid definition -- please fix");
1434       }
1435
1436       file_list[list_pos].token = config_list[i].token;
1437       file_list[list_pos].default_filename = config_list[i].value;
1438     }
1439   }
1440
1441   if (list_pos != num_file_list_entries - 1)
1442     Error(ERR_EXIT, "inconsistant config list information -- please fix");
1443
1444   return file_list;
1445 }
1446
1447 static void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
1448 {
1449   struct FileInfo *file_list = artwork_info->file_list;
1450   struct ConfigInfo *suffix_list = artwork_info->suffix_list;
1451   int num_file_list_entries = artwork_info->num_file_list_entries;
1452   int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
1453   char *filename = getCustomArtworkConfigFilename(artwork_info->type);
1454   struct SetupFileList *setup_file_list;
1455   int i, j;
1456
1457 #if 0
1458   printf("GOT CUSTOM ARTWORK CONFIG FILE '%s'\n", filename);
1459 #endif
1460
1461   /* always start with reliable default values */
1462   for (i=0; i<num_file_list_entries; i++)
1463   {
1464     if (file_list[i].filename != NULL)
1465       free(file_list[i].filename);
1466     file_list[i].filename = NULL;
1467
1468     for (j=0; j<num_suffix_list_entries; j++)
1469       file_list[i].parameter[j] = file_list[i].default_parameter[j];
1470   }
1471
1472   if (filename == NULL)
1473     return;
1474
1475   if ((setup_file_list = loadSetupFileList(filename)))
1476   {
1477     for (i=0; i<num_file_list_entries; i++)
1478     {
1479       char *filename = getTokenValue(setup_file_list, file_list[i].token);
1480
1481       if (filename == NULL)
1482         filename = file_list[i].default_filename;
1483       file_list[i].filename = getStringCopy(filename);
1484
1485       for (j=0; j<num_suffix_list_entries; j++)
1486       {
1487         char *token = getStringCat2(file_list[i].token, suffix_list[j].token);
1488         char *value = getTokenValue(setup_file_list, token);
1489
1490         if (value != NULL)
1491           file_list[i].parameter[j] = atoi(value);
1492
1493         free(token);
1494       }
1495     }
1496
1497     freeSetupFileList(setup_file_list);
1498
1499 #if 0
1500     for (i=0; i<num_file_list_entries; i++)
1501     {
1502       printf("'%s' ", file_list[i].token);
1503       if (file_list[i].filename)
1504         printf("-> '%s'\n", file_list[i].filename);
1505       else
1506         printf("-> UNDEFINED [-> '%s']\n", file_list[i].default_filename);
1507     }
1508 #endif
1509   }
1510 }
1511
1512 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
1513                                    struct ListNodeInfo **listnode)
1514 {
1515   if (*listnode)
1516   {
1517     char *filename = (*listnode)->source_filename;
1518
1519 #if 0
1520     printf("[decrementing reference counter of artwork '%s']\n", filename);
1521 #endif
1522
1523     if (--(*listnode)->num_references <= 0)
1524     {
1525 #if 0
1526       printf("[deleting artwork '%s']\n", filename);
1527 #endif
1528
1529       deleteNodeFromList(&artwork_info->content_list, filename,
1530                          artwork_info->free_artwork);
1531     }
1532
1533     *listnode = NULL;
1534   }
1535 }
1536
1537 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
1538                                     struct ListNodeInfo **listnode,
1539                                     char *basename)
1540 {
1541   char *init_text[] =
1542   { "",
1543     "Loading graphics:",
1544     "Loading sounds:",
1545     "Loading music:"
1546   };
1547
1548   ListNode *node;
1549   char *filename = getCustomArtworkFilename(basename, artwork_info->type);
1550
1551   if (filename == NULL)
1552   {
1553     Error(ERR_WARN, "cannot find artwork file '%s'", basename);
1554     return;
1555   }
1556
1557   /* check if the old and the new artwork file are the same */
1558   if (*listnode && strcmp((*listnode)->source_filename, filename) == 0)
1559   {
1560     /* The old and new artwork are the same (have the same filename and path).
1561        This usually means that this artwork does not exist in this artwork set
1562        and a fallback to the existing artwork is done. */
1563
1564 #if 0
1565     printf("[artwork '%s' already exists (same list entry)]\n", filename);
1566 #endif
1567
1568     return;
1569   }
1570
1571   /* delete existing artwork file entry */
1572   deleteArtworkListEntry(artwork_info, listnode);
1573
1574   /* check if the new artwork file already exists in the list of artworks */
1575   if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
1576   {
1577 #if 0
1578       printf("[artwork '%s' already exists (other list entry)]\n", filename);
1579 #endif
1580
1581       *listnode = (struct ListNodeInfo *)node->content;
1582       (*listnode)->num_references++;
1583
1584       return;
1585   }
1586
1587   DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
1588   DrawInitText(basename, 150, FC_YELLOW);
1589
1590   if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
1591   {
1592 #if 0
1593       printf("[adding new artwork '%s']\n", filename);
1594 #endif
1595
1596     (*listnode)->num_references = 1;
1597     addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
1598                   *listnode);
1599   }
1600 }
1601
1602 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
1603                               struct ListNodeInfo **listnode,
1604                               char *basename)
1605 {
1606 #if 0
1607   char *filename = getCustomArtworkFilename(basename, artwork_info->type);
1608 #endif
1609
1610 #if 0
1611   printf("GOT CUSTOM ARTWORK FILE '%s'\n", filename);
1612 #endif
1613
1614   if (strcmp(basename, UNDEFINED_FILENAME) == 0)
1615   {
1616     deleteArtworkListEntry(artwork_info, listnode);
1617     return;
1618   }
1619
1620 #if 0
1621   if (filename == NULL)
1622   {
1623     Error(ERR_WARN, "cannot find artwork file '%s'", basename);
1624     return;
1625   }
1626
1627   replaceArtworkListEntry(artwork_info, listnode, filename);
1628 #else
1629   replaceArtworkListEntry(artwork_info, listnode, basename);
1630 #endif
1631 }
1632
1633 static void LoadArtworkToList(struct ArtworkListInfo *artwork_info,
1634                               char *basename, int list_pos)
1635 {
1636   if (artwork_info->artwork_list == NULL ||
1637       list_pos >= artwork_info->num_file_list_entries)
1638     return;
1639
1640 #if 0
1641   printf("loading artwork '%s' ...  [%d]\n",
1642          basename, getNumNodes(artwork_info->content_list));
1643 #endif
1644
1645   LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[list_pos],
1646                     basename);
1647
1648 #if 0
1649   printf("loading artwork '%s' done [%d]\n",
1650          basename, getNumNodes(artwork_info->content_list));
1651 #endif
1652 }
1653
1654 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
1655 {
1656 #if 0
1657   static struct
1658   {
1659     char *text;
1660     boolean do_it;
1661   }
1662   draw_init[] =
1663   {
1664     { "",                       FALSE },
1665     { "Loading graphics:",      TRUE },
1666     { "Loading sounds:",        TRUE },
1667     { "Loading music:",         TRUE }
1668   };
1669 #endif
1670
1671   int num_file_list_entries = artwork_info->num_file_list_entries;
1672   struct FileInfo *file_list = artwork_info->file_list;
1673   int i;
1674
1675   LoadArtworkConfig(artwork_info);
1676
1677 #if 0
1678   if (draw_init[artwork_info->type].do_it)
1679     DrawInitText(draw_init[artwork_info->type].text, 120, FC_GREEN);
1680 #endif
1681
1682 #if 0
1683   printf("DEBUG: reloading %d artwork files ...\n", num_file_list_entries);
1684 #endif
1685
1686   for(i=0; i<num_file_list_entries; i++)
1687   {
1688 #if 0
1689     if (draw_init[artwork_info->type].do_it)
1690       DrawInitText(file_list[i].token, 150, FC_YELLOW);
1691 #endif
1692
1693     LoadArtworkToList(artwork_info, file_list[i].filename, i);
1694
1695 #if 0
1696     printf("DEBUG:   loading artwork file '%s'...\n", file_list[i].filename);
1697 #endif
1698   }
1699
1700 #if 0
1701   draw_init[artwork_info->type].do_it = FALSE;
1702 #endif
1703
1704   /*
1705   printf("list size == %d\n", getNumNodes(artwork_info->content_list));
1706   */
1707
1708 #if 0
1709   dumpList(artwork_info->content_list);
1710 #endif
1711 }
1712
1713 void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info)
1714 {
1715   int i;
1716
1717   if (artwork_info->artwork_list == NULL)
1718     return;
1719
1720 #if 0
1721   printf("%s: FREEING ARTWORK ...\n",
1722          IS_CHILD_PROCESS(audio.mixer_pid) ? "CHILD" : "PARENT");
1723 #endif
1724
1725   for(i=0; i<artwork_info->num_file_list_entries; i++)
1726     deleteArtworkListEntry(artwork_info, &artwork_info->artwork_list[i]);
1727
1728 #if 0
1729   printf("%s: FREEING ARTWORK -- DONE\n",
1730          IS_CHILD_PROCESS(audio.mixer_pid) ? "CHILD" : "PARENT");
1731 #endif
1732
1733   free(artwork_info->artwork_list);
1734
1735   artwork_info->artwork_list = NULL;
1736   artwork_info->num_file_list_entries = 0;
1737 }
1738
1739
1740 /* ========================================================================= */
1741 /* functions only needed for non-Unix (non-command-line) systems             */
1742 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt")    */
1743 /* ========================================================================= */
1744
1745 #if defined(PLATFORM_MSDOS)
1746
1747 #define ERROR_FILENAME          "stderr.txt"
1748
1749 void initErrorFile()
1750 {
1751   unlink(ERROR_FILENAME);
1752 }
1753
1754 FILE *openErrorFile()
1755 {
1756   return fopen(ERROR_FILENAME, MODE_APPEND);
1757 }
1758
1759 void dumpErrorFile()
1760 {
1761   FILE *error_file = fopen(ERROR_FILENAME, MODE_READ);
1762
1763   if (error_file != NULL)
1764   {
1765     while (!feof(error_file))
1766       fputc(fgetc(error_file), stderr);
1767
1768     fclose(error_file);
1769   }
1770 }
1771 #endif
1772
1773
1774 /* ========================================================================= */
1775 /* the following is only for debugging purpose and normally not used         */
1776 /* ========================================================================= */
1777
1778 #define DEBUG_NUM_TIMESTAMPS    3
1779
1780 void debug_print_timestamp(int counter_nr, char *message)
1781 {
1782   static long counter[DEBUG_NUM_TIMESTAMPS][2];
1783
1784   if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
1785     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
1786
1787   counter[counter_nr][0] = Counter();
1788
1789   if (message)
1790     printf("%s %.2f seconds\n", message,
1791            (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
1792
1793   counter[counter_nr][1] = Counter();
1794 }