rnd-20020906-3-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 char *getStringCopy(char *s)
407 {
408   char *s_copy;
409
410   if (s == NULL)
411     return NULL;
412
413   s_copy = checked_malloc(strlen(s) + 1);
414
415   strcpy(s_copy, s);
416   return s_copy;
417 }
418
419 char *getStringToLower(char *s)
420 {
421   char *s_copy = checked_malloc(strlen(s) + 1);
422   char *s_ptr = s_copy;
423
424   while (*s)
425     *s_ptr++ = tolower(*s++);
426   *s_ptr = '\0';
427
428   return s_copy;
429 }
430
431 void GetOptions(char *argv[])
432 {
433   char **options_left = &argv[1];
434
435   /* initialize global program options */
436   options.display_name = NULL;
437   options.server_host = NULL;
438   options.server_port = 0;
439   options.ro_base_directory = RO_BASE_PATH;
440   options.rw_base_directory = RW_BASE_PATH;
441   options.level_directory = RO_BASE_PATH "/" LEVELS_DIRECTORY;
442   options.graphics_directory = RO_BASE_PATH "/" GRAPHICS_DIRECTORY;
443   options.sounds_directory = RO_BASE_PATH "/" SOUNDS_DIRECTORY;
444   options.music_directory = RO_BASE_PATH "/" MUSIC_DIRECTORY;
445   options.serveronly = FALSE;
446   options.network = FALSE;
447   options.verbose = FALSE;
448   options.debug = FALSE;
449   options.debug_command = NULL;
450
451   while (*options_left)
452   {
453     char option_str[MAX_OPTION_LEN];
454     char *option = options_left[0];
455     char *next_option = options_left[1];
456     char *option_arg = NULL;
457     int option_len = strlen(option);
458
459     if (option_len >= MAX_OPTION_LEN)
460       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
461
462     strcpy(option_str, option);                 /* copy argument into buffer */
463     option = option_str;
464
465     if (strcmp(option, "--") == 0)              /* stop scanning arguments */
466       break;
467
468     if (strncmp(option, "--", 2) == 0)          /* treat '--' like '-' */
469       option++;
470
471     option_arg = strchr(option, '=');
472     if (option_arg == NULL)                     /* no '=' in option */
473       option_arg = next_option;
474     else
475     {
476       *option_arg++ = '\0';                     /* cut argument from option */
477       if (*option_arg == '\0')                  /* no argument after '=' */
478         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
479     }
480
481     option_len = strlen(option);
482
483     if (strcmp(option, "-") == 0)
484       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
485     else if (strncmp(option, "-help", option_len) == 0)
486     {
487       printf("Usage: %s [options] [<server host> [<server port>]]\n"
488              "Options:\n"
489              "  -d, --display <host>[:<scr>]  X server display\n"
490              "  -b, --basepath <directory>    alternative base directory\n"
491              "  -l, --level <directory>       alternative level directory\n"
492              "  -g, --graphics <directory>    alternative graphics directory\n"
493              "  -s, --sounds <directory>      alternative sounds directory\n"
494              "  -m, --music <directory>       alternative music directory\n"
495              "  -n, --network                 network multiplayer game\n"
496              "      --serveronly              only start network server\n"
497              "  -v, --verbose                 verbose mode\n"
498              "      --debug                   display debugging information\n",
499              program.command_basename);
500
501       if (options.debug)
502         printf("      --debug-command <command> execute special command\n");
503
504       exit(0);
505     }
506     else if (strncmp(option, "-display", option_len) == 0)
507     {
508       if (option_arg == NULL)
509         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
510
511       options.display_name = option_arg;
512       if (option_arg == next_option)
513         options_left++;
514     }
515     else if (strncmp(option, "-basepath", option_len) == 0)
516     {
517       if (option_arg == NULL)
518         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
519
520       /* this should be extended to separate options for ro and rw data */
521       options.ro_base_directory = option_arg;
522       options.rw_base_directory = option_arg;
523       if (option_arg == next_option)
524         options_left++;
525
526       /* adjust path for level directory accordingly */
527       options.level_directory =
528         getPath2(options.ro_base_directory, LEVELS_DIRECTORY);
529     }
530     else if (strncmp(option, "-levels", option_len) == 0)
531     {
532       if (option_arg == NULL)
533         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
534
535       options.level_directory = option_arg;
536       if (option_arg == next_option)
537         options_left++;
538     }
539     else if (strncmp(option, "-graphics", option_len) == 0)
540     {
541       if (option_arg == NULL)
542         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
543
544       options.graphics_directory = option_arg;
545       if (option_arg == next_option)
546         options_left++;
547     }
548     else if (strncmp(option, "-sounds", option_len) == 0)
549     {
550       if (option_arg == NULL)
551         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
552
553       options.sounds_directory = option_arg;
554       if (option_arg == next_option)
555         options_left++;
556     }
557     else if (strncmp(option, "-music", option_len) == 0)
558     {
559       if (option_arg == NULL)
560         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
561
562       options.music_directory = option_arg;
563       if (option_arg == next_option)
564         options_left++;
565     }
566     else if (strncmp(option, "-network", option_len) == 0)
567     {
568       options.network = TRUE;
569     }
570     else if (strncmp(option, "-serveronly", option_len) == 0)
571     {
572       options.serveronly = TRUE;
573     }
574     else if (strncmp(option, "-verbose", option_len) == 0)
575     {
576       options.verbose = TRUE;
577     }
578     else if (strncmp(option, "-debug", option_len) == 0)
579     {
580       options.debug = TRUE;
581     }
582     else if (strncmp(option, "-debug-command", option_len) == 0)
583     {
584       if (option_arg == NULL)
585         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
586
587       options.debug_command = option_arg;
588       if (option_arg == next_option)
589         options_left++;
590     }
591     else if (*option == '-')
592     {
593       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
594     }
595     else if (options.server_host == NULL)
596     {
597       options.server_host = *options_left;
598     }
599     else if (options.server_port == 0)
600     {
601       options.server_port = atoi(*options_left);
602       if (options.server_port < 1024)
603         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
604     }
605     else
606       Error(ERR_EXIT_HELP, "too many arguments");
607
608     options_left++;
609   }
610 }
611
612 /* used by SetError() and GetError() to store internal error messages */
613 static char internal_error[1024];       /* this is bad */
614
615 void SetError(char *format, ...)
616 {
617   va_list ap;
618
619   va_start(ap, format);
620   vsprintf(internal_error, format, ap);
621   va_end(ap);
622 }
623
624 char *GetError()
625 {
626   return internal_error;
627 }
628
629 void Error(int mode, char *format, ...)
630 {
631   char *process_name = "";
632   FILE *error = stderr;
633   char *newline = "\n";
634
635   /* display warnings only when running in verbose mode */
636   if (mode & ERR_WARN && !options.verbose)
637     return;
638
639 #if defined(PLATFORM_MSDOS)
640   newline = "\r\n";
641
642   if ((error = openErrorFile()) == NULL)
643   {
644     printf("Cannot write to error output file!%s", newline);
645     program.exit_function(1);
646   }
647 #endif
648
649   if (mode & ERR_SOUND_SERVER)
650     process_name = " sound server";
651   else if (mode & ERR_NETWORK_SERVER)
652     process_name = " network server";
653   else if (mode & ERR_NETWORK_CLIENT)
654     process_name = " network client **";
655
656   if (format)
657   {
658     va_list ap;
659
660     fprintf(error, "%s%s: ", program.command_basename, process_name);
661
662     if (mode & ERR_WARN)
663       fprintf(error, "warning: ");
664
665     va_start(ap, format);
666     vfprintf(error, format, ap);
667     va_end(ap);
668   
669     fprintf(error, "%s", newline);
670   }
671   
672   if (mode & ERR_HELP)
673     fprintf(error, "%s: Try option '--help' for more information.%s",
674             program.command_basename, newline);
675
676   if (mode & ERR_EXIT)
677     fprintf(error, "%s%s: aborting%s",
678             program.command_basename, process_name, newline);
679
680   if (error != stderr)
681     fclose(error);
682
683   if (mode & ERR_EXIT)
684   {
685     if (mode & ERR_FROM_SERVER)
686       exit(1);                          /* child process: normal exit */
687     else
688       program.exit_function(1);         /* main process: clean up stuff */
689   }
690 }
691
692 void *checked_malloc(unsigned long size)
693 {
694   void *ptr;
695
696   ptr = malloc(size);
697
698   if (ptr == NULL)
699     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
700
701   return ptr;
702 }
703
704 void *checked_calloc(unsigned long size)
705 {
706   void *ptr;
707
708   ptr = calloc(1, size);
709
710   if (ptr == NULL)
711     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
712
713   return ptr;
714 }
715
716 void *checked_realloc(void *ptr, unsigned long size)
717 {
718   ptr = realloc(ptr, size);
719
720   if (ptr == NULL)
721     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
722
723   return ptr;
724 }
725
726 inline void swap_numbers(int *i1, int *i2)
727 {
728   int help = *i1;
729
730   *i1 = *i2;
731   *i2 = help;
732 }
733
734 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
735 {
736   int help_x = *x1;
737   int help_y = *y1;
738
739   *x1 = *x2;
740   *x2 = help_x;
741
742   *y1 = *y2;
743   *y2 = help_y;
744 }
745
746 short getFile16BitInteger(FILE *file, int byte_order)
747 {
748   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
749     return ((fgetc(file) <<  8) |
750             (fgetc(file) <<  0));
751   else           /* BYTE_ORDER_LITTLE_ENDIAN */
752     return ((fgetc(file) <<  0) |
753             (fgetc(file) <<  8));
754 }
755
756 void putFile16BitInteger(FILE *file, short value, int byte_order)
757 {
758   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
759   {
760     fputc((value >>  8) & 0xff, file);
761     fputc((value >>  0) & 0xff, file);
762   }
763   else           /* BYTE_ORDER_LITTLE_ENDIAN */
764   {
765     fputc((value >>  0) & 0xff, file);
766     fputc((value >>  8) & 0xff, file);
767   }
768 }
769
770 int getFile32BitInteger(FILE *file, int byte_order)
771 {
772   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
773     return ((fgetc(file) << 24) |
774             (fgetc(file) << 16) |
775             (fgetc(file) <<  8) |
776             (fgetc(file) <<  0));
777   else           /* BYTE_ORDER_LITTLE_ENDIAN */
778     return ((fgetc(file) <<  0) |
779             (fgetc(file) <<  8) |
780             (fgetc(file) << 16) |
781             (fgetc(file) << 24));
782 }
783
784 void putFile32BitInteger(FILE *file, int value, int byte_order)
785 {
786   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
787   {
788     fputc((value >> 24) & 0xff, file);
789     fputc((value >> 16) & 0xff, file);
790     fputc((value >>  8) & 0xff, file);
791     fputc((value >>  0) & 0xff, file);
792   }
793   else           /* BYTE_ORDER_LITTLE_ENDIAN */
794   {
795     fputc((value >>  0) & 0xff, file);
796     fputc((value >>  8) & 0xff, file);
797     fputc((value >> 16) & 0xff, file);
798     fputc((value >> 24) & 0xff, file);
799   }
800 }
801
802 boolean getFileChunk(FILE *file, char *chunk_name, int *chunk_size,
803                      int byte_order)
804 {
805   const int chunk_name_length = 4;
806
807   /* read chunk name */
808   fgets(chunk_name, chunk_name_length + 1, file);
809
810   if (chunk_size != NULL)
811   {
812     /* read chunk size */
813     *chunk_size = getFile32BitInteger(file, byte_order);
814   }
815
816   return (feof(file) || ferror(file) ? FALSE : TRUE);
817 }
818
819 void putFileChunk(FILE *file, char *chunk_name, int chunk_size,
820                   int byte_order)
821 {
822   /* write chunk name */
823   fputs(chunk_name, file);
824
825   if (chunk_size >= 0)
826   {
827     /* write chunk size */
828     putFile32BitInteger(file, chunk_size, byte_order);
829   }
830 }
831
832 int getFileVersion(FILE *file)
833 {
834   int version_major, version_minor, version_patch;
835
836   version_major = fgetc(file);
837   version_minor = fgetc(file);
838   version_patch = fgetc(file);
839   fgetc(file);          /* not used */
840
841   return VERSION_IDENT(version_major, version_minor, version_patch);
842 }
843
844 void putFileVersion(FILE *file, int version)
845 {
846   int version_major = VERSION_MAJOR(version);
847   int version_minor = VERSION_MINOR(version);
848   int version_patch = VERSION_PATCH(version);
849
850   fputc(version_major, file);
851   fputc(version_minor, file);
852   fputc(version_patch, file);
853   fputc(0, file);       /* not used */
854 }
855
856 void ReadUnusedBytesFromFile(FILE *file, unsigned long bytes)
857 {
858   while (bytes-- && !feof(file))
859     fgetc(file);
860 }
861
862 void WriteUnusedBytesToFile(FILE *file, unsigned long bytes)
863 {
864   while (bytes--)
865     fputc(0, file);
866 }
867
868
869 /* ------------------------------------------------------------------------- */
870 /* functions to translate key identifiers between different format           */
871 /* ------------------------------------------------------------------------- */
872
873 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
874 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
875 #define TRANSLATE_KEYNAME_TO_KEYSYM     2
876 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  3
877
878 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
879 {
880   static struct
881   {
882     Key key;
883     char *x11name;
884     char *name;
885   } translate_key[] =
886   {
887     /* normal cursor keys */
888     { KSYM_Left,        "XK_Left",              "cursor left" },
889     { KSYM_Right,       "XK_Right",             "cursor right" },
890     { KSYM_Up,          "XK_Up",                "cursor up" },
891     { KSYM_Down,        "XK_Down",              "cursor down" },
892
893     /* keypad cursor keys */
894 #ifdef KSYM_KP_Left
895     { KSYM_KP_Left,     "XK_KP_Left",           "keypad left" },
896     { KSYM_KP_Right,    "XK_KP_Right",          "keypad right" },
897     { KSYM_KP_Up,       "XK_KP_Up",             "keypad up" },
898     { KSYM_KP_Down,     "XK_KP_Down",           "keypad down" },
899 #endif
900
901     /* other keypad keys */
902 #ifdef KSYM_KP_Enter
903     { KSYM_KP_Enter,    "XK_KP_Enter",          "keypad enter" },
904     { KSYM_KP_Add,      "XK_KP_Add",            "keypad +" },
905     { KSYM_KP_Subtract, "XK_KP_Subtract",       "keypad -" },
906     { KSYM_KP_Multiply, "XK_KP_Multiply",       "keypad mltply" },
907     { KSYM_KP_Divide,   "XK_KP_Divide",         "keypad /" },
908     { KSYM_KP_Separator,"XK_KP_Separator",      "keypad ," },
909 #endif
910
911     /* modifier keys */
912     { KSYM_Shift_L,     "XK_Shift_L",           "left shift" },
913     { KSYM_Shift_R,     "XK_Shift_R",           "right shift" },
914     { KSYM_Control_L,   "XK_Control_L",         "left control" },
915     { KSYM_Control_R,   "XK_Control_R",         "right control" },
916     { KSYM_Meta_L,      "XK_Meta_L",            "left meta" },
917     { KSYM_Meta_R,      "XK_Meta_R",            "right meta" },
918     { KSYM_Alt_L,       "XK_Alt_L",             "left alt" },
919     { KSYM_Alt_R,       "XK_Alt_R",             "right alt" },
920     { KSYM_Super_L,     "XK_Super_L",           "left super" },  /* Win-L */
921     { KSYM_Super_R,     "XK_Super_R",           "right super" }, /* Win-R */
922     { KSYM_Mode_switch, "XK_Mode_switch",       "mode switch" }, /* Alt-R */
923     { KSYM_Multi_key,   "XK_Multi_key",         "multi key" },   /* Ctrl-R */
924
925     /* some special keys */
926     { KSYM_BackSpace,   "XK_BackSpace",         "backspace" },
927     { KSYM_Delete,      "XK_Delete",            "delete" },
928     { KSYM_Insert,      "XK_Insert",            "insert" },
929     { KSYM_Tab,         "XK_Tab",               "tab" },
930     { KSYM_Home,        "XK_Home",              "home" },
931     { KSYM_End,         "XK_End",               "end" },
932     { KSYM_Page_Up,     "XK_Page_Up",           "page up" },
933     { KSYM_Page_Down,   "XK_Page_Down",         "page down" },
934     { KSYM_Menu,        "XK_Menu",              "menu" },        /* Win-Menu */
935
936     /* ASCII 0x20 to 0x40 keys (except numbers) */
937     { KSYM_space,       "XK_space",             "space" },
938     { KSYM_exclam,      "XK_exclam",            "!" },
939     { KSYM_quotedbl,    "XK_quotedbl",          "\"" },
940     { KSYM_numbersign,  "XK_numbersign",        "#" },
941     { KSYM_dollar,      "XK_dollar",            "$" },
942     { KSYM_percent,     "XK_percent",           "%" },
943     { KSYM_ampersand,   "XK_ampersand",         "&" },
944     { KSYM_apostrophe,  "XK_apostrophe",        "'" },
945     { KSYM_parenleft,   "XK_parenleft",         "(" },
946     { KSYM_parenright,  "XK_parenright",        ")" },
947     { KSYM_asterisk,    "XK_asterisk",          "*" },
948     { KSYM_plus,        "XK_plus",              "+" },
949     { KSYM_comma,       "XK_comma",             "," },
950     { KSYM_minus,       "XK_minus",             "-" },
951     { KSYM_period,      "XK_period",            "." },
952     { KSYM_slash,       "XK_slash",             "/" },
953     { KSYM_colon,       "XK_colon",             ":" },
954     { KSYM_semicolon,   "XK_semicolon",         ";" },
955     { KSYM_less,        "XK_less",              "<" },
956     { KSYM_equal,       "XK_equal",             "=" },
957     { KSYM_greater,     "XK_greater",           ">" },
958     { KSYM_question,    "XK_question",          "?" },
959     { KSYM_at,          "XK_at",                "@" },
960
961     /* more ASCII keys */
962     { KSYM_bracketleft, "XK_bracketleft",       "[" },
963     { KSYM_backslash,   "XK_backslash",         "backslash" },
964     { KSYM_bracketright,"XK_bracketright",      "]" },
965     { KSYM_asciicircum, "XK_asciicircum",       "circumflex" },
966     { KSYM_underscore,  "XK_underscore",        "_" },
967     { KSYM_grave,       "XK_grave",             "grave" },
968     { KSYM_quoteleft,   "XK_quoteleft",         "quote left" },
969     { KSYM_braceleft,   "XK_braceleft",         "brace left" },
970     { KSYM_bar,         "XK_bar",               "bar" },
971     { KSYM_braceright,  "XK_braceright",        "brace right" },
972     { KSYM_asciitilde,  "XK_asciitilde",        "ascii tilde" },
973
974     /* special (non-ASCII) keys */
975     { KSYM_Adiaeresis,  "XK_Adiaeresis",        "Ä" },
976     { KSYM_Odiaeresis,  "XK_Odiaeresis",        "Ö" },
977     { KSYM_Udiaeresis,  "XK_Udiaeresis",        "Ãœ" },
978     { KSYM_adiaeresis,  "XK_adiaeresis",        "ä" },
979     { KSYM_odiaeresis,  "XK_odiaeresis",        "ö" },
980     { KSYM_udiaeresis,  "XK_udiaeresis",        "ü" },
981     { KSYM_ssharp,      "XK_ssharp",            "sharp s" },
982
983     /* end-of-array identifier */
984     { 0,                NULL,                   NULL }
985   };
986
987   int i;
988
989   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
990   {
991     static char name_buffer[30];
992     Key key = *keysym;
993
994     if (key >= KSYM_A && key <= KSYM_Z)
995       sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
996     else if (key >= KSYM_a && key <= KSYM_z)
997       sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
998     else if (key >= KSYM_0 && key <= KSYM_9)
999       sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1000     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1001       sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1002     else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1003       sprintf(name_buffer, "function F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1004     else if (key == KSYM_UNDEFINED)
1005       strcpy(name_buffer, "(undefined)");
1006     else
1007     {
1008       i = 0;
1009
1010       do
1011       {
1012         if (key == translate_key[i].key)
1013         {
1014           strcpy(name_buffer, translate_key[i].name);
1015           break;
1016         }
1017       }
1018       while (translate_key[++i].name);
1019
1020       if (!translate_key[i].name)
1021         strcpy(name_buffer, "(unknown)");
1022     }
1023
1024     *name = name_buffer;
1025   }
1026   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1027   {
1028     static char name_buffer[30];
1029     Key key = *keysym;
1030
1031     if (key >= KSYM_A && key <= KSYM_Z)
1032       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1033     else if (key >= KSYM_a && key <= KSYM_z)
1034       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1035     else if (key >= KSYM_0 && key <= KSYM_9)
1036       sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1037     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1038       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1039     else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1040       sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1041     else if (key == KSYM_UNDEFINED)
1042       strcpy(name_buffer, "[undefined]");
1043     else
1044     {
1045       i = 0;
1046
1047       do
1048       {
1049         if (key == translate_key[i].key)
1050         {
1051           strcpy(name_buffer, translate_key[i].x11name);
1052           break;
1053         }
1054       }
1055       while (translate_key[++i].x11name);
1056
1057       if (!translate_key[i].x11name)
1058         sprintf(name_buffer, "0x%04lx", (unsigned long)key);
1059     }
1060
1061     *x11name = name_buffer;
1062   }
1063   else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1064   {
1065     Key key = KSYM_UNDEFINED;
1066
1067     i = 0;
1068     do
1069     {
1070       if (strcmp(translate_key[i].name, *name) == 0)
1071       {
1072         key = translate_key[i].key;
1073         break;
1074       }
1075     }
1076     while (translate_key[++i].x11name);
1077
1078     if (key == KSYM_UNDEFINED)
1079       Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1080
1081     *keysym = key;
1082   }
1083   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1084   {
1085     Key key = KSYM_UNDEFINED;
1086     char *name_ptr = *x11name;
1087
1088     if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
1089     {
1090       char c = name_ptr[3];
1091
1092       if (c >= 'A' && c <= 'Z')
1093         key = KSYM_A + (Key)(c - 'A');
1094       else if (c >= 'a' && c <= 'z')
1095         key = KSYM_a + (Key)(c - 'a');
1096       else if (c >= '0' && c <= '9')
1097         key = KSYM_0 + (Key)(c - '0');
1098     }
1099     else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
1100     {
1101       char c = name_ptr[6];
1102
1103       if (c >= '0' && c <= '9')
1104         key = KSYM_0 + (Key)(c - '0');
1105     }
1106     else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
1107     {
1108       char c1 = name_ptr[4];
1109       char c2 = name_ptr[5];
1110       int d = 0;
1111
1112       if ((c1 >= '0' && c1 <= '9') &&
1113           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1114         d = atoi(&name_ptr[4]);
1115
1116       if (d >= 1 && d <= KSYM_NUM_FKEYS)
1117         key = KSYM_F1 + (Key)(d - 1);
1118     }
1119     else if (strncmp(name_ptr, "XK_", 3) == 0)
1120     {
1121       i = 0;
1122
1123       do
1124       {
1125         if (strcmp(name_ptr, translate_key[i].x11name) == 0)
1126         {
1127           key = translate_key[i].key;
1128           break;
1129         }
1130       }
1131       while (translate_key[++i].x11name);
1132     }
1133     else if (strncmp(name_ptr, "0x", 2) == 0)
1134     {
1135       unsigned long value = 0;
1136
1137       name_ptr += 2;
1138
1139       while (name_ptr)
1140       {
1141         char c = *name_ptr++;
1142         int d = -1;
1143
1144         if (c >= '0' && c <= '9')
1145           d = (int)(c - '0');
1146         else if (c >= 'a' && c <= 'f')
1147           d = (int)(c - 'a' + 10);
1148         else if (c >= 'A' && c <= 'F')
1149           d = (int)(c - 'A' + 10);
1150
1151         if (d == -1)
1152         {
1153           value = -1;
1154           break;
1155         }
1156
1157         value = value * 16 + d;
1158       }
1159
1160       if (value != -1)
1161         key = (Key)value;
1162     }
1163
1164     *keysym = key;
1165   }
1166 }
1167
1168 char *getKeyNameFromKey(Key key)
1169 {
1170   char *name;
1171
1172   translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1173   return name;
1174 }
1175
1176 char *getX11KeyNameFromKey(Key key)
1177 {
1178   char *x11name;
1179
1180   translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1181   return x11name;
1182 }
1183
1184 Key getKeyFromKeyName(char *name)
1185 {
1186   Key key;
1187
1188   translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1189   return key;
1190 }
1191
1192 Key getKeyFromX11KeyName(char *x11name)
1193 {
1194   Key key;
1195
1196   translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1197   return key;
1198 }
1199
1200 char getCharFromKey(Key key)
1201 {
1202   char *keyname = getKeyNameFromKey(key);
1203   char letter = 0;
1204
1205   if (strlen(keyname) == 1)
1206     letter = keyname[0];
1207   else if (strcmp(keyname, "space") == 0)
1208     letter = ' ';
1209   else if (strcmp(keyname, "circumflex") == 0)
1210     letter = '^';
1211
1212   return letter;
1213 }
1214
1215
1216 /* ========================================================================= */
1217 /* functions for generic lists                                               */
1218 /* ========================================================================= */
1219
1220 ListNode *newListNode()
1221 {
1222   return checked_calloc(sizeof(ListNode));
1223 }
1224
1225 void addNodeToList(ListNode **node_first, char *key, void *content)
1226 {
1227   ListNode *node_new = newListNode();
1228
1229 #if 0
1230   printf("LIST: adding node with key '%s'\n", key);
1231 #endif
1232
1233   node_new->key = getStringCopy(key);
1234   node_new->content = content;
1235   node_new->next = *node_first;
1236   *node_first = node_new;
1237 }
1238
1239 void deleteNodeFromList(ListNode **node_first, char *key,
1240                         void (*destructor_function)(void *))
1241 {
1242   if (node_first == NULL || *node_first == NULL)
1243     return;
1244
1245 #if 0
1246   printf("[CHECKING LIST KEY '%s' == '%s']\n",
1247          (*node_first)->key, key);
1248 #endif
1249
1250   if (strcmp((*node_first)->key, key) == 0)
1251   {
1252 #if 0
1253     printf("[DELETING LIST ENTRY]\n");
1254 #endif
1255
1256     free((*node_first)->key);
1257     if (destructor_function)
1258       destructor_function((*node_first)->content);
1259     *node_first = (*node_first)->next;
1260   }
1261   else
1262     deleteNodeFromList(&(*node_first)->next, key, destructor_function);
1263 }
1264
1265 ListNode *getNodeFromKey(ListNode *node_first, char *key)
1266 {
1267   if (node_first == NULL)
1268     return NULL;
1269
1270   if (strcmp(node_first->key, key) == 0)
1271     return node_first;
1272   else
1273     return getNodeFromKey(node_first->next, key);
1274 }
1275
1276 int getNumNodes(ListNode *node_first)
1277 {
1278   return (node_first ? 1 + getNumNodes(node_first->next) : 0);
1279 }
1280
1281 void dumpList(ListNode *node_first)
1282 {
1283   ListNode *node = node_first;
1284
1285   while (node)
1286   {
1287     printf("['%s' (%d)]\n", node->key,
1288            ((struct ListNodeInfo *)node->content)->num_references);
1289     node = node->next;
1290   }
1291
1292   printf("[%d nodes]\n", getNumNodes(node_first));
1293 }
1294
1295
1296 /* ========================================================================= */
1297 /* functions for checking filenames                                          */
1298 /* ========================================================================= */
1299
1300 boolean FileIsGraphic(char *filename)
1301 {
1302   if (strlen(filename) > 4 &&
1303       strcmp(&filename[strlen(filename) - 4], ".pcx") == 0)
1304     return TRUE;
1305
1306   return FALSE;
1307 }
1308
1309 boolean FileIsSound(char *basename)
1310 {
1311   if (strlen(basename) > 4 &&
1312       strcmp(&basename[strlen(basename) - 4], ".wav") == 0)
1313     return TRUE;
1314
1315   return FALSE;
1316 }
1317
1318 boolean FileIsMusic(char *basename)
1319 {
1320   /* "music" can be a WAV (loop) file or (if compiled with SDL) a MOD file */
1321
1322   if (FileIsSound(basename))
1323     return TRUE;
1324
1325 #if defined(TARGET_SDL)
1326   if (strlen(basename) > 4 &&
1327       (strcmp(&basename[strlen(basename) - 4], ".mod") == 0 ||
1328        strcmp(&basename[strlen(basename) - 4], ".MOD") == 0 ||
1329        strncmp(basename, "mod.", 4) == 0 ||
1330        strncmp(basename, "MOD.", 4) == 0))
1331     return TRUE;
1332 #endif
1333
1334   return FALSE;
1335 }
1336
1337 boolean FileIsArtworkType(char *basename, int type)
1338 {
1339   if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(basename)) ||
1340       (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(basename)) ||
1341       (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(basename)))
1342     return TRUE;
1343
1344   return FALSE;
1345 }
1346
1347 /* ========================================================================= */
1348 /* functions for loading artwork configuration information                   */
1349 /* ========================================================================= */
1350
1351 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
1352                                            char *suffix_list[],
1353                                            int num_list_entries)
1354 {
1355   struct FileInfo *file_list =
1356     checked_calloc(num_list_entries * sizeof(struct FileInfo));
1357   int list_pos = 0;
1358   int i, j;
1359
1360   for (i=0; config_list[i].token != NULL; i++)
1361   {
1362     int len_config_token = strlen(config_list[i].token);
1363     boolean is_file_entry = TRUE;
1364
1365     for (j=0; suffix_list[j] != NULL; j++)
1366     {
1367       int len_suffix = strlen(suffix_list[j]);
1368
1369       if (len_suffix < len_config_token &&
1370           strcmp(&config_list[i].token[len_config_token - len_suffix],
1371                  suffix_list[j]) == 0)
1372       {
1373         is_file_entry = FALSE;
1374         break;
1375       }
1376     }
1377
1378     if (is_file_entry)
1379     {
1380       if (list_pos >= num_list_entries)
1381         Error(ERR_EXIT, "inconsistant config list information -- please fix");
1382
1383       file_list[list_pos].token = config_list[i].token;
1384       file_list[list_pos].default_filename = config_list[i].value;
1385
1386       list_pos++;
1387     }
1388   }
1389
1390   if (list_pos != num_list_entries)
1391     Error(ERR_EXIT, "inconsistant config list information -- please fix");
1392
1393   return file_list;
1394 }
1395
1396 static void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
1397 {
1398   int num_list_entries = artwork_info->num_list_entries;
1399   struct FileInfo *file_list = artwork_info->file_list;
1400   char *filename = getCustomArtworkConfigFilename(artwork_info->type);
1401   struct SetupFileList *setup_file_list;
1402   int i;
1403
1404 #if 0
1405   printf("GOT CUSTOM ARTWORK CONFIG FILE '%s'\n", filename);
1406 #endif
1407
1408   /* always start with reliable default values */
1409   for (i=0; i<num_list_entries; i++)
1410     file_list[i].filename = NULL;
1411
1412   if (filename == NULL)
1413     return;
1414
1415   if ((setup_file_list = loadSetupFileList(filename)))
1416   {
1417     for (i=0; i<num_list_entries; i++)
1418       file_list[i].filename =
1419         getStringCopy(getTokenValue(setup_file_list, file_list[i].token));
1420
1421     freeSetupFileList(setup_file_list);
1422
1423 #if 0
1424     for (i=0; i<num_list_entries; i++)
1425     {
1426       printf("'%s' ", file_list[i].token);
1427       if (file_list[i].filename)
1428         printf("-> '%s'\n", file_list[i].filename);
1429       else
1430         printf("-> UNDEFINED [-> '%s']\n", file_list[i].default_filename);
1431     }
1432 #endif
1433   }
1434 }
1435
1436 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
1437                                    struct ListNodeInfo **listnode)
1438 {
1439   if (*listnode)
1440   {
1441     char *filename = (*listnode)->source_filename;
1442
1443 #if 0
1444     printf("[decrementing reference counter of artwork '%s']\n", filename);
1445 #endif
1446
1447     if (--(*listnode)->num_references <= 0)
1448     {
1449 #if 0
1450       printf("[deleting artwork '%s']\n", filename);
1451 #endif
1452
1453       deleteNodeFromList(&artwork_info->content_list, filename,
1454                          artwork_info->free_artwork);
1455     }
1456
1457     *listnode = NULL;
1458   }
1459 }
1460
1461 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
1462                                     struct ListNodeInfo **listnode,
1463                                     char *filename)
1464 {
1465   ListNode *node;
1466
1467   /* check if the old and the new artwork file are the same */
1468   if (*listnode && strcmp((*listnode)->source_filename, filename) == 0)
1469   {
1470     /* The old and new artwork are the same (have the same filename and path).
1471        This usually means that this artwork does not exist in this artwork set
1472        and a fallback to the existing artwork is done. */
1473
1474 #if 0
1475     printf("[artwork '%s' already exists (same list entry)]\n", filename);
1476 #endif
1477
1478     return;
1479   }
1480
1481   /* delete existing artwork file entry */
1482   deleteArtworkListEntry(artwork_info, listnode);
1483
1484   /* check if the new artwork file already exists in the list of artworks */
1485   if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
1486   {
1487 #if 0
1488       printf("[artwork '%s' already exists (other list entry)]\n", filename);
1489 #endif
1490
1491       *listnode = (struct ListNodeInfo *)node->content;
1492       (*listnode)->num_references++;
1493   }
1494   else if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
1495   {
1496     (*listnode)->num_references = 1;
1497     addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
1498                   *listnode);
1499   }
1500 }
1501
1502 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
1503                               struct ListNodeInfo **listnode,
1504                               char *basename)
1505 {
1506   char *filename = getCustomArtworkFilename(basename, artwork_info->type);
1507
1508 #if 0
1509   printf("GOT CUSTOM ARTWORK FILE '%s'\n", filename);
1510 #endif
1511
1512   if (strcmp(basename, UNDEFINED_FILENAME) == 0)
1513   {
1514     deleteArtworkListEntry(artwork_info, listnode);
1515     return;
1516   }
1517
1518   if (filename == NULL)
1519   {
1520     Error(ERR_WARN, "cannot find artwork file '%s'", basename);
1521     return;
1522   }
1523
1524   replaceArtworkListEntry(artwork_info, listnode, filename);
1525 }
1526
1527 static void LoadArtworkToList(struct ArtworkListInfo *artwork_info,
1528                               char *basename, int list_pos)
1529 {
1530   if (artwork_info->artwork_list == NULL ||
1531       list_pos >= artwork_info->num_list_entries)
1532     return;
1533
1534 #if 0
1535   printf("loading artwork '%s' ...  [%d]\n",
1536          basename, getNumNodes(artwork_info->content_list));
1537 #endif
1538
1539   LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[list_pos],
1540                     basename);
1541
1542 #if 0
1543   printf("loading artwork '%s' done [%d]\n",
1544          basename, getNumNodes(artwork_info->content_list));
1545 #endif
1546 }
1547
1548 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
1549 {
1550   static struct
1551   {
1552     char *text;
1553     boolean do_it;
1554   }
1555   draw_init[] =
1556   {
1557     { "",                       FALSE },
1558     { "Loading graphics:",      TRUE },
1559     { "Loading sounds:",        TRUE },
1560     { "Loading music:",         TRUE }
1561   };
1562
1563   int num_list_entries = artwork_info->num_list_entries;
1564   struct FileInfo *file_list = artwork_info->file_list;
1565   int i;
1566
1567   LoadArtworkConfig(artwork_info);
1568
1569   if (draw_init[artwork_info->type].do_it)
1570     DrawInitText(draw_init[artwork_info->type].text, 120, FC_GREEN);
1571
1572 #if 0
1573   printf("DEBUG: reloading %d sounds ...\n", num_list_entries);
1574 #endif
1575
1576   for(i=0; i<num_list_entries; i++)
1577   {
1578     if (draw_init[artwork_info->type].do_it)
1579       DrawInitText(file_list[i].token, 150, FC_YELLOW);
1580
1581     if (file_list[i].filename)
1582       LoadArtworkToList(artwork_info, file_list[i].filename, i);
1583     else
1584       LoadArtworkToList(artwork_info, file_list[i].default_filename, i);
1585   }
1586
1587   draw_init[artwork_info->type].do_it = FALSE;
1588
1589   /*
1590   printf("list size == %d\n", getNumNodes(artwork_info->content_list));
1591   */
1592
1593 #if 0
1594   dumpList(artwork_info->content_list);
1595 #endif
1596 }
1597
1598 void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info)
1599 {
1600   int i;
1601
1602   if (artwork_info->artwork_list == NULL)
1603     return;
1604
1605 #if 0
1606   printf("%s: FREEING ARTWORK ...\n",
1607          IS_CHILD_PROCESS(audio.mixer_pid) ? "CHILD" : "PARENT");
1608 #endif
1609
1610   for(i=0; i<artwork_info->num_list_entries; i++)
1611     deleteArtworkListEntry(artwork_info, &artwork_info->artwork_list[i]);
1612
1613 #if 0
1614   printf("%s: FREEING ARTWORK -- DONE\n",
1615          IS_CHILD_PROCESS(audio.mixer_pid) ? "CHILD" : "PARENT");
1616 #endif
1617
1618   free(artwork_info->artwork_list);
1619
1620   artwork_info->artwork_list = NULL;
1621   artwork_info->num_list_entries = 0;
1622 }
1623
1624
1625 /* ========================================================================= */
1626 /* functions only needed for non-Unix (non-command-line) systems             */
1627 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt")    */
1628 /* ========================================================================= */
1629
1630 #if defined(PLATFORM_MSDOS)
1631
1632 #define ERROR_FILENAME          "stderr.txt"
1633
1634 void initErrorFile()
1635 {
1636   unlink(ERROR_FILENAME);
1637 }
1638
1639 FILE *openErrorFile()
1640 {
1641   return fopen(ERROR_FILENAME, MODE_APPEND);
1642 }
1643
1644 void dumpErrorFile()
1645 {
1646   FILE *error_file = fopen(ERROR_FILENAME, MODE_READ);
1647
1648   if (error_file != NULL)
1649   {
1650     while (!feof(error_file))
1651       fputc(fgetc(error_file), stderr);
1652
1653     fclose(error_file);
1654   }
1655 }
1656 #endif
1657
1658
1659 /* ========================================================================= */
1660 /* the following is only for debugging purpose and normally not used         */
1661 /* ========================================================================= */
1662
1663 #define DEBUG_NUM_TIMESTAMPS    3
1664
1665 void debug_print_timestamp(int counter_nr, char *message)
1666 {
1667   static long counter[DEBUG_NUM_TIMESTAMPS][2];
1668
1669   if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
1670     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
1671
1672   counter[counter_nr][0] = Counter();
1673
1674   if (message)
1675     printf("%s %.2f seconds\n", message,
1676            (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
1677
1678   counter[counter_nr][1] = Counter();
1679 }