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