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