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