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