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