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