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