rnd-20030405-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 (random_linux_libc(nr) % max);
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.execute_command = NULL;
577   options.serveronly = FALSE;
578   options.network = FALSE;
579   options.verbose = FALSE;
580   options.debug = FALSE;
581
582 #if !defined(PLATFORM_UNIX)
583   if (*options_left == NULL)    /* no options given -- enable verbose mode */
584     options.verbose = TRUE;
585 #endif
586
587   while (*options_left)
588   {
589     char option_str[MAX_OPTION_LEN];
590     char *option = options_left[0];
591     char *next_option = options_left[1];
592     char *option_arg = NULL;
593     int option_len = strlen(option);
594
595     if (option_len >= MAX_OPTION_LEN)
596       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
597
598     strcpy(option_str, option);                 /* copy argument into buffer */
599     option = option_str;
600
601     if (strcmp(option, "--") == 0)              /* stop scanning arguments */
602       break;
603
604     if (strncmp(option, "--", 2) == 0)          /* treat '--' like '-' */
605       option++;
606
607     option_arg = strchr(option, '=');
608     if (option_arg == NULL)                     /* no '=' in option */
609       option_arg = next_option;
610     else
611     {
612       *option_arg++ = '\0';                     /* cut argument from option */
613       if (*option_arg == '\0')                  /* no argument after '=' */
614         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
615     }
616
617     option_len = strlen(option);
618
619     if (strcmp(option, "-") == 0)
620       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
621     else if (strncmp(option, "-help", option_len) == 0)
622     {
623       printUsage();
624
625       exit(0);
626     }
627     else if (strncmp(option, "-display", option_len) == 0)
628     {
629       if (option_arg == NULL)
630         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
631
632       options.display_name = option_arg;
633       if (option_arg == next_option)
634         options_left++;
635     }
636     else if (strncmp(option, "-basepath", option_len) == 0)
637     {
638       if (option_arg == NULL)
639         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
640
641       /* this should be extended to separate options for ro and rw data */
642       options.ro_base_directory = option_arg;
643       options.rw_base_directory = option_arg;
644       if (option_arg == next_option)
645         options_left++;
646
647       /* adjust path for level directory accordingly */
648       options.level_directory =
649         getPath2(options.ro_base_directory, LEVELS_DIRECTORY);
650     }
651     else if (strncmp(option, "-levels", option_len) == 0)
652     {
653       if (option_arg == NULL)
654         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
655
656       options.level_directory = option_arg;
657       if (option_arg == next_option)
658         options_left++;
659     }
660     else if (strncmp(option, "-graphics", option_len) == 0)
661     {
662       if (option_arg == NULL)
663         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
664
665       options.graphics_directory = option_arg;
666       if (option_arg == next_option)
667         options_left++;
668     }
669     else if (strncmp(option, "-sounds", option_len) == 0)
670     {
671       if (option_arg == NULL)
672         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
673
674       options.sounds_directory = option_arg;
675       if (option_arg == next_option)
676         options_left++;
677     }
678     else if (strncmp(option, "-music", option_len) == 0)
679     {
680       if (option_arg == NULL)
681         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
682
683       options.music_directory = option_arg;
684       if (option_arg == next_option)
685         options_left++;
686     }
687     else if (strncmp(option, "-network", option_len) == 0)
688     {
689       options.network = TRUE;
690     }
691     else if (strncmp(option, "-serveronly", option_len) == 0)
692     {
693       options.serveronly = TRUE;
694     }
695     else if (strncmp(option, "-verbose", option_len) == 0)
696     {
697       options.verbose = TRUE;
698     }
699     else if (strncmp(option, "-debug", option_len) == 0)
700     {
701       options.debug = TRUE;
702     }
703     else if (strncmp(option, "-execute", option_len) == 0)
704     {
705       if (option_arg == NULL)
706         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
707
708       options.execute_command = option_arg;
709       if (option_arg == next_option)
710         options_left++;
711     }
712     else if (*option == '-')
713     {
714       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
715     }
716     else if (options.server_host == NULL)
717     {
718       options.server_host = *options_left;
719     }
720     else if (options.server_port == 0)
721     {
722       options.server_port = atoi(*options_left);
723       if (options.server_port < 1024)
724         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
725     }
726     else
727       Error(ERR_EXIT_HELP, "too many arguments");
728
729     options_left++;
730   }
731 }
732
733
734 /* ------------------------------------------------------------------------- */
735 /* error handling functions                                                  */
736 /* ------------------------------------------------------------------------- */
737
738 /* used by SetError() and GetError() to store internal error messages */
739 static char internal_error[1024];       /* this is bad */
740
741 void SetError(char *format, ...)
742 {
743   va_list ap;
744
745   va_start(ap, format);
746   vsprintf(internal_error, format, ap);
747   va_end(ap);
748 }
749
750 char *GetError()
751 {
752   return internal_error;
753 }
754
755 void Error(int mode, char *format, ...)
756 {
757   static boolean last_line_was_separator = FALSE;
758   char *process_name = "";
759   FILE *error = stderr;
760   char *newline = "\n";
761
762   /* display warnings only when running in verbose mode */
763   if (mode & ERR_WARN && !options.verbose)
764     return;
765
766   if (mode == ERR_RETURN_LINE)
767   {
768     if (!last_line_was_separator)
769       fprintf_line(error, format, 79);
770
771     last_line_was_separator = TRUE;
772
773     return;
774   }
775
776   last_line_was_separator = FALSE;
777
778 #if defined(PLATFORM_MSDOS)
779   newline = "\r\n";
780
781   if ((error = openErrorFile()) == NULL)
782   {
783     printf("Cannot write to error output file!%s", newline);
784     program.exit_function(1);
785   }
786 #endif
787
788   if (mode & ERR_SOUND_SERVER)
789     process_name = " sound server";
790   else if (mode & ERR_NETWORK_SERVER)
791     process_name = " network server";
792   else if (mode & ERR_NETWORK_CLIENT)
793     process_name = " network client **";
794
795   if (format)
796   {
797     va_list ap;
798
799     fprintf(error, "%s%s: ", program.command_basename, process_name);
800
801     if (mode & ERR_WARN)
802       fprintf(error, "warning: ");
803
804     va_start(ap, format);
805     vfprintf(error, format, ap);
806     va_end(ap);
807   
808     fprintf(error, "%s", newline);
809   }
810   
811   if (mode & ERR_HELP)
812     fprintf(error, "%s: Try option '--help' for more information.%s",
813             program.command_basename, newline);
814
815   if (mode & ERR_EXIT)
816     fprintf(error, "%s%s: aborting%s",
817             program.command_basename, process_name, newline);
818
819   if (error != stderr)
820     fclose(error);
821
822   if (mode & ERR_EXIT)
823   {
824     if (mode & ERR_FROM_SERVER)
825       exit(1);                          /* child process: normal exit */
826     else
827       program.exit_function(1);         /* main process: clean up stuff */
828   }
829 }
830
831
832 /* ------------------------------------------------------------------------- */
833 /* memory allocation functions                                               */
834 /* ------------------------------------------------------------------------- */
835
836 void *checked_malloc(unsigned long size)
837 {
838   void *ptr;
839
840   ptr = malloc(size);
841
842   if (ptr == NULL)
843     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
844
845   return ptr;
846 }
847
848 void *checked_calloc(unsigned long size)
849 {
850   void *ptr;
851
852   ptr = calloc(1, size);
853
854   if (ptr == NULL)
855     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
856
857   return ptr;
858 }
859
860 void *checked_realloc(void *ptr, unsigned long size)
861 {
862   ptr = realloc(ptr, size);
863
864   if (ptr == NULL)
865     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
866
867   return ptr;
868 }
869
870
871 /* ------------------------------------------------------------------------- */
872 /* various helper functions                                                  */
873 /* ------------------------------------------------------------------------- */
874
875 inline void swap_numbers(int *i1, int *i2)
876 {
877   int help = *i1;
878
879   *i1 = *i2;
880   *i2 = help;
881 }
882
883 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
884 {
885   int help_x = *x1;
886   int help_y = *y1;
887
888   *x1 = *x2;
889   *x2 = help_x;
890
891   *y1 = *y2;
892   *y2 = help_y;
893 }
894
895 short getFile16BitInteger(FILE *file, int byte_order)
896 {
897   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
898     return ((fgetc(file) <<  8) |
899             (fgetc(file) <<  0));
900   else           /* BYTE_ORDER_LITTLE_ENDIAN */
901     return ((fgetc(file) <<  0) |
902             (fgetc(file) <<  8));
903 }
904
905 void putFile16BitInteger(FILE *file, short value, int byte_order)
906 {
907   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
908   {
909     fputc((value >>  8) & 0xff, file);
910     fputc((value >>  0) & 0xff, file);
911   }
912   else           /* BYTE_ORDER_LITTLE_ENDIAN */
913   {
914     fputc((value >>  0) & 0xff, file);
915     fputc((value >>  8) & 0xff, file);
916   }
917 }
918
919 int getFile32BitInteger(FILE *file, int byte_order)
920 {
921   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
922     return ((fgetc(file) << 24) |
923             (fgetc(file) << 16) |
924             (fgetc(file) <<  8) |
925             (fgetc(file) <<  0));
926   else           /* BYTE_ORDER_LITTLE_ENDIAN */
927     return ((fgetc(file) <<  0) |
928             (fgetc(file) <<  8) |
929             (fgetc(file) << 16) |
930             (fgetc(file) << 24));
931 }
932
933 void putFile32BitInteger(FILE *file, int value, int byte_order)
934 {
935   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
936   {
937     fputc((value >> 24) & 0xff, file);
938     fputc((value >> 16) & 0xff, file);
939     fputc((value >>  8) & 0xff, file);
940     fputc((value >>  0) & 0xff, file);
941   }
942   else           /* BYTE_ORDER_LITTLE_ENDIAN */
943   {
944     fputc((value >>  0) & 0xff, file);
945     fputc((value >>  8) & 0xff, file);
946     fputc((value >> 16) & 0xff, file);
947     fputc((value >> 24) & 0xff, file);
948   }
949 }
950
951 boolean getFileChunk(FILE *file, char *chunk_name, int *chunk_size,
952                      int byte_order)
953 {
954   const int chunk_name_length = 4;
955
956   /* read chunk name */
957   fgets(chunk_name, chunk_name_length + 1, file);
958
959   if (chunk_size != NULL)
960   {
961     /* read chunk size */
962     *chunk_size = getFile32BitInteger(file, byte_order);
963   }
964
965   return (feof(file) || ferror(file) ? FALSE : TRUE);
966 }
967
968 void putFileChunk(FILE *file, char *chunk_name, int chunk_size,
969                   int byte_order)
970 {
971   /* write chunk name */
972   fputs(chunk_name, file);
973
974   if (chunk_size >= 0)
975   {
976     /* write chunk size */
977     putFile32BitInteger(file, chunk_size, byte_order);
978   }
979 }
980
981 int getFileVersion(FILE *file)
982 {
983   int version_major, version_minor, version_patch;
984
985   version_major = fgetc(file);
986   version_minor = fgetc(file);
987   version_patch = fgetc(file);
988   fgetc(file);          /* not used */
989
990   return VERSION_IDENT(version_major, version_minor, version_patch);
991 }
992
993 void putFileVersion(FILE *file, int version)
994 {
995   int version_major = VERSION_MAJOR(version);
996   int version_minor = VERSION_MINOR(version);
997   int version_patch = VERSION_PATCH(version);
998
999   fputc(version_major, file);
1000   fputc(version_minor, file);
1001   fputc(version_patch, file);
1002   fputc(0, file);       /* not used */
1003 }
1004
1005 void ReadUnusedBytesFromFile(FILE *file, unsigned long bytes)
1006 {
1007   while (bytes-- && !feof(file))
1008     fgetc(file);
1009 }
1010
1011 void WriteUnusedBytesToFile(FILE *file, unsigned long bytes)
1012 {
1013   while (bytes--)
1014     fputc(0, file);
1015 }
1016
1017
1018 /* ------------------------------------------------------------------------- */
1019 /* functions to translate key identifiers between different format           */
1020 /* ------------------------------------------------------------------------- */
1021
1022 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
1023 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
1024 #define TRANSLATE_KEYNAME_TO_KEYSYM     2
1025 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  3
1026
1027 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
1028 {
1029   static struct
1030   {
1031     Key key;
1032     char *x11name;
1033     char *name;
1034   } translate_key[] =
1035   {
1036     /* normal cursor keys */
1037     { KSYM_Left,        "XK_Left",              "cursor left" },
1038     { KSYM_Right,       "XK_Right",             "cursor right" },
1039     { KSYM_Up,          "XK_Up",                "cursor up" },
1040     { KSYM_Down,        "XK_Down",              "cursor down" },
1041
1042     /* keypad cursor keys */
1043 #ifdef KSYM_KP_Left
1044     { KSYM_KP_Left,     "XK_KP_Left",           "keypad left" },
1045     { KSYM_KP_Right,    "XK_KP_Right",          "keypad right" },
1046     { KSYM_KP_Up,       "XK_KP_Up",             "keypad up" },
1047     { KSYM_KP_Down,     "XK_KP_Down",           "keypad down" },
1048 #endif
1049
1050     /* other keypad keys */
1051 #ifdef KSYM_KP_Enter
1052     { KSYM_KP_Enter,    "XK_KP_Enter",          "keypad enter" },
1053     { KSYM_KP_Add,      "XK_KP_Add",            "keypad +" },
1054     { KSYM_KP_Subtract, "XK_KP_Subtract",       "keypad -" },
1055     { KSYM_KP_Multiply, "XK_KP_Multiply",       "keypad mltply" },
1056     { KSYM_KP_Divide,   "XK_KP_Divide",         "keypad /" },
1057     { KSYM_KP_Separator,"XK_KP_Separator",      "keypad ," },
1058 #endif
1059
1060     /* modifier keys */
1061     { KSYM_Shift_L,     "XK_Shift_L",           "left shift" },
1062     { KSYM_Shift_R,     "XK_Shift_R",           "right shift" },
1063     { KSYM_Control_L,   "XK_Control_L",         "left control" },
1064     { KSYM_Control_R,   "XK_Control_R",         "right control" },
1065     { KSYM_Meta_L,      "XK_Meta_L",            "left meta" },
1066     { KSYM_Meta_R,      "XK_Meta_R",            "right meta" },
1067     { KSYM_Alt_L,       "XK_Alt_L",             "left alt" },
1068     { KSYM_Alt_R,       "XK_Alt_R",             "right alt" },
1069     { KSYM_Super_L,     "XK_Super_L",           "left super" },  /* Win-L */
1070     { KSYM_Super_R,     "XK_Super_R",           "right super" }, /* Win-R */
1071     { KSYM_Mode_switch, "XK_Mode_switch",       "mode switch" }, /* Alt-R */
1072     { KSYM_Multi_key,   "XK_Multi_key",         "multi key" },   /* Ctrl-R */
1073
1074     /* some special keys */
1075     { KSYM_BackSpace,   "XK_BackSpace",         "backspace" },
1076     { KSYM_Delete,      "XK_Delete",            "delete" },
1077     { KSYM_Insert,      "XK_Insert",            "insert" },
1078     { KSYM_Tab,         "XK_Tab",               "tab" },
1079     { KSYM_Home,        "XK_Home",              "home" },
1080     { KSYM_End,         "XK_End",               "end" },
1081     { KSYM_Page_Up,     "XK_Page_Up",           "page up" },
1082     { KSYM_Page_Down,   "XK_Page_Down",         "page down" },
1083     { KSYM_Menu,        "XK_Menu",              "menu" },        /* Win-Menu */
1084
1085     /* ASCII 0x20 to 0x40 keys (except numbers) */
1086     { KSYM_space,       "XK_space",             "space" },
1087     { KSYM_exclam,      "XK_exclam",            "!" },
1088     { KSYM_quotedbl,    "XK_quotedbl",          "\"" },
1089     { KSYM_numbersign,  "XK_numbersign",        "#" },
1090     { KSYM_dollar,      "XK_dollar",            "$" },
1091     { KSYM_percent,     "XK_percent",           "%" },
1092     { KSYM_ampersand,   "XK_ampersand",         "&" },
1093     { KSYM_apostrophe,  "XK_apostrophe",        "'" },
1094     { KSYM_parenleft,   "XK_parenleft",         "(" },
1095     { KSYM_parenright,  "XK_parenright",        ")" },
1096     { KSYM_asterisk,    "XK_asterisk",          "*" },
1097     { KSYM_plus,        "XK_plus",              "+" },
1098     { KSYM_comma,       "XK_comma",             "," },
1099     { KSYM_minus,       "XK_minus",             "-" },
1100     { KSYM_period,      "XK_period",            "." },
1101     { KSYM_slash,       "XK_slash",             "/" },
1102     { KSYM_colon,       "XK_colon",             ":" },
1103     { KSYM_semicolon,   "XK_semicolon",         ";" },
1104     { KSYM_less,        "XK_less",              "<" },
1105     { KSYM_equal,       "XK_equal",             "=" },
1106     { KSYM_greater,     "XK_greater",           ">" },
1107     { KSYM_question,    "XK_question",          "?" },
1108     { KSYM_at,          "XK_at",                "@" },
1109
1110     /* more ASCII keys */
1111     { KSYM_bracketleft, "XK_bracketleft",       "[" },
1112     { KSYM_backslash,   "XK_backslash",         "backslash" },
1113     { KSYM_bracketright,"XK_bracketright",      "]" },
1114     { KSYM_asciicircum, "XK_asciicircum",       "circumflex" },
1115     { KSYM_underscore,  "XK_underscore",        "_" },
1116     { KSYM_grave,       "XK_grave",             "grave" },
1117     { KSYM_quoteleft,   "XK_quoteleft",         "quote left" },
1118     { KSYM_braceleft,   "XK_braceleft",         "brace left" },
1119     { KSYM_bar,         "XK_bar",               "bar" },
1120     { KSYM_braceright,  "XK_braceright",        "brace right" },
1121     { KSYM_asciitilde,  "XK_asciitilde",        "ascii tilde" },
1122
1123     /* special (non-ASCII) keys */
1124     { KSYM_Adiaeresis,  "XK_Adiaeresis",        "Ä" },
1125     { KSYM_Odiaeresis,  "XK_Odiaeresis",        "Ö" },
1126     { KSYM_Udiaeresis,  "XK_Udiaeresis",        "Ãœ" },
1127     { KSYM_adiaeresis,  "XK_adiaeresis",        "ä" },
1128     { KSYM_odiaeresis,  "XK_odiaeresis",        "ö" },
1129     { KSYM_udiaeresis,  "XK_udiaeresis",        "ü" },
1130     { KSYM_ssharp,      "XK_ssharp",            "sharp s" },
1131
1132     /* end-of-array identifier */
1133     { 0,                NULL,                   NULL }
1134   };
1135
1136   int i;
1137
1138   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
1139   {
1140     static char name_buffer[30];
1141     Key key = *keysym;
1142
1143     if (key >= KSYM_A && key <= KSYM_Z)
1144       sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
1145     else if (key >= KSYM_a && key <= KSYM_z)
1146       sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
1147     else if (key >= KSYM_0 && key <= KSYM_9)
1148       sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
1149     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1150       sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1151     else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1152       sprintf(name_buffer, "function F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1153     else if (key == KSYM_UNDEFINED)
1154       strcpy(name_buffer, "(undefined)");
1155     else
1156     {
1157       i = 0;
1158
1159       do
1160       {
1161         if (key == translate_key[i].key)
1162         {
1163           strcpy(name_buffer, translate_key[i].name);
1164           break;
1165         }
1166       }
1167       while (translate_key[++i].name);
1168
1169       if (!translate_key[i].name)
1170         strcpy(name_buffer, "(unknown)");
1171     }
1172
1173     *name = name_buffer;
1174   }
1175   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1176   {
1177     static char name_buffer[30];
1178     Key key = *keysym;
1179
1180     if (key >= KSYM_A && key <= KSYM_Z)
1181       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1182     else if (key >= KSYM_a && key <= KSYM_z)
1183       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1184     else if (key >= KSYM_0 && key <= KSYM_9)
1185       sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1186     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1187       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1188     else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1189       sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1190     else if (key == KSYM_UNDEFINED)
1191       strcpy(name_buffer, "[undefined]");
1192     else
1193     {
1194       i = 0;
1195
1196       do
1197       {
1198         if (key == translate_key[i].key)
1199         {
1200           strcpy(name_buffer, translate_key[i].x11name);
1201           break;
1202         }
1203       }
1204       while (translate_key[++i].x11name);
1205
1206       if (!translate_key[i].x11name)
1207         sprintf(name_buffer, "0x%04lx", (unsigned long)key);
1208     }
1209
1210     *x11name = name_buffer;
1211   }
1212   else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1213   {
1214     Key key = KSYM_UNDEFINED;
1215
1216     i = 0;
1217     do
1218     {
1219       if (strcmp(translate_key[i].name, *name) == 0)
1220       {
1221         key = translate_key[i].key;
1222         break;
1223       }
1224     }
1225     while (translate_key[++i].x11name);
1226
1227     if (key == KSYM_UNDEFINED)
1228       Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1229
1230     *keysym = key;
1231   }
1232   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1233   {
1234     Key key = KSYM_UNDEFINED;
1235     char *name_ptr = *x11name;
1236
1237     if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
1238     {
1239       char c = name_ptr[3];
1240
1241       if (c >= 'A' && c <= 'Z')
1242         key = KSYM_A + (Key)(c - 'A');
1243       else if (c >= 'a' && c <= 'z')
1244         key = KSYM_a + (Key)(c - 'a');
1245       else if (c >= '0' && c <= '9')
1246         key = KSYM_0 + (Key)(c - '0');
1247     }
1248     else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
1249     {
1250       char c = name_ptr[6];
1251
1252       if (c >= '0' && c <= '9')
1253         key = KSYM_0 + (Key)(c - '0');
1254     }
1255     else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
1256     {
1257       char c1 = name_ptr[4];
1258       char c2 = name_ptr[5];
1259       int d = 0;
1260
1261       if ((c1 >= '0' && c1 <= '9') &&
1262           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1263         d = atoi(&name_ptr[4]);
1264
1265       if (d >= 1 && d <= KSYM_NUM_FKEYS)
1266         key = KSYM_F1 + (Key)(d - 1);
1267     }
1268     else if (strncmp(name_ptr, "XK_", 3) == 0)
1269     {
1270       i = 0;
1271
1272       do
1273       {
1274         if (strcmp(name_ptr, translate_key[i].x11name) == 0)
1275         {
1276           key = translate_key[i].key;
1277           break;
1278         }
1279       }
1280       while (translate_key[++i].x11name);
1281     }
1282     else if (strncmp(name_ptr, "0x", 2) == 0)
1283     {
1284       unsigned long value = 0;
1285
1286       name_ptr += 2;
1287
1288       while (name_ptr)
1289       {
1290         char c = *name_ptr++;
1291         int d = -1;
1292
1293         if (c >= '0' && c <= '9')
1294           d = (int)(c - '0');
1295         else if (c >= 'a' && c <= 'f')
1296           d = (int)(c - 'a' + 10);
1297         else if (c >= 'A' && c <= 'F')
1298           d = (int)(c - 'A' + 10);
1299
1300         if (d == -1)
1301         {
1302           value = -1;
1303           break;
1304         }
1305
1306         value = value * 16 + d;
1307       }
1308
1309       if (value != -1)
1310         key = (Key)value;
1311     }
1312
1313     *keysym = key;
1314   }
1315 }
1316
1317 char *getKeyNameFromKey(Key key)
1318 {
1319   char *name;
1320
1321   translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1322   return name;
1323 }
1324
1325 char *getX11KeyNameFromKey(Key key)
1326 {
1327   char *x11name;
1328
1329   translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1330   return x11name;
1331 }
1332
1333 Key getKeyFromKeyName(char *name)
1334 {
1335   Key key;
1336
1337   translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1338   return key;
1339 }
1340
1341 Key getKeyFromX11KeyName(char *x11name)
1342 {
1343   Key key;
1344
1345   translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1346   return key;
1347 }
1348
1349 char getCharFromKey(Key key)
1350 {
1351   char *keyname = getKeyNameFromKey(key);
1352   char letter = 0;
1353
1354   if (strlen(keyname) == 1)
1355     letter = keyname[0];
1356   else if (strcmp(keyname, "space") == 0)
1357     letter = ' ';
1358   else if (strcmp(keyname, "circumflex") == 0)
1359     letter = '^';
1360
1361   return letter;
1362 }
1363
1364
1365 /* ------------------------------------------------------------------------- */
1366 /* functions to translate string identifiers to integer or boolean value     */
1367 /* ------------------------------------------------------------------------- */
1368
1369 int get_integer_from_string(char *s)
1370 {
1371   static char *number_text[][3] =
1372   {
1373     { "0", "zero", "null", },
1374     { "1", "one", "first" },
1375     { "2", "two", "second" },
1376     { "3", "three", "third" },
1377     { "4", "four", "fourth" },
1378     { "5", "five", "fifth" },
1379     { "6", "six", "sixth" },
1380     { "7", "seven", "seventh" },
1381     { "8", "eight", "eighth" },
1382     { "9", "nine", "ninth" },
1383     { "10", "ten", "tenth" },
1384     { "11", "eleven", "eleventh" },
1385     { "12", "twelve", "twelfth" },
1386   };
1387
1388   int i, j;
1389   char *s_lower = getStringToLower(s);
1390   int result = -1;
1391
1392   for (i=0; i<13; i++)
1393     for (j=0; j<3; j++)
1394       if (strcmp(s_lower, number_text[i][j]) == 0)
1395         result = i;
1396
1397   if (result == -1)
1398     result = atoi(s);
1399
1400   free(s_lower);
1401
1402   return result;
1403 }
1404
1405 boolean get_boolean_from_string(char *s)
1406 {
1407   char *s_lower = getStringToLower(s);
1408   boolean result = FALSE;
1409
1410   if (strcmp(s_lower, "true") == 0 ||
1411       strcmp(s_lower, "yes") == 0 ||
1412       strcmp(s_lower, "on") == 0 ||
1413       get_integer_from_string(s) == 1)
1414     result = TRUE;
1415
1416   free(s_lower);
1417
1418   return result;
1419 }
1420
1421
1422 /* ------------------------------------------------------------------------- */
1423 /* functions for generic lists                                               */
1424 /* ------------------------------------------------------------------------- */
1425
1426 ListNode *newListNode()
1427 {
1428   return checked_calloc(sizeof(ListNode));
1429 }
1430
1431 void addNodeToList(ListNode **node_first, char *key, void *content)
1432 {
1433   ListNode *node_new = newListNode();
1434
1435 #if 0
1436   printf("LIST: adding node with key '%s'\n", key);
1437 #endif
1438
1439   node_new->key = getStringCopy(key);
1440   node_new->content = content;
1441   node_new->next = *node_first;
1442   *node_first = node_new;
1443 }
1444
1445 void deleteNodeFromList(ListNode **node_first, char *key,
1446                         void (*destructor_function)(void *))
1447 {
1448   if (node_first == NULL || *node_first == NULL)
1449     return;
1450
1451 #if 0
1452   printf("[CHECKING LIST KEY '%s' == '%s']\n",
1453          (*node_first)->key, key);
1454 #endif
1455
1456   if (strcmp((*node_first)->key, key) == 0)
1457   {
1458 #if 0
1459     printf("[DELETING LIST ENTRY]\n");
1460 #endif
1461
1462     free((*node_first)->key);
1463     if (destructor_function)
1464       destructor_function((*node_first)->content);
1465     *node_first = (*node_first)->next;
1466   }
1467   else
1468     deleteNodeFromList(&(*node_first)->next, key, destructor_function);
1469 }
1470
1471 ListNode *getNodeFromKey(ListNode *node_first, char *key)
1472 {
1473   if (node_first == NULL)
1474     return NULL;
1475
1476   if (strcmp(node_first->key, key) == 0)
1477     return node_first;
1478   else
1479     return getNodeFromKey(node_first->next, key);
1480 }
1481
1482 int getNumNodes(ListNode *node_first)
1483 {
1484   return (node_first ? 1 + getNumNodes(node_first->next) : 0);
1485 }
1486
1487 void dumpList(ListNode *node_first)
1488 {
1489   ListNode *node = node_first;
1490
1491   while (node)
1492   {
1493     printf("['%s' (%d)]\n", node->key,
1494            ((struct ListNodeInfo *)node->content)->num_references);
1495     node = node->next;
1496   }
1497
1498   printf("[%d nodes]\n", getNumNodes(node_first));
1499 }
1500
1501
1502 /* ------------------------------------------------------------------------- */
1503 /* functions for checking filenames                                          */
1504 /* ------------------------------------------------------------------------- */
1505
1506 boolean FileIsGraphic(char *filename)
1507 {
1508   if (strlen(filename) > 4 &&
1509       strcmp(&filename[strlen(filename) - 4], ".pcx") == 0)
1510     return TRUE;
1511
1512   return FALSE;
1513 }
1514
1515 boolean FileIsSound(char *basename)
1516 {
1517   if (strlen(basename) > 4 &&
1518       strcmp(&basename[strlen(basename) - 4], ".wav") == 0)
1519     return TRUE;
1520
1521   return FALSE;
1522 }
1523
1524 boolean FileIsMusic(char *basename)
1525 {
1526   /* "music" can be a WAV (loop) file or (if compiled with SDL) a MOD file */
1527
1528   if (FileIsSound(basename))
1529     return TRUE;
1530
1531 #if defined(TARGET_SDL)
1532   if (strlen(basename) > 4 &&
1533       (strcmp(&basename[strlen(basename) - 4], ".mod") == 0 ||
1534        strcmp(&basename[strlen(basename) - 4], ".MOD") == 0 ||
1535        strncmp(basename, "mod.", 4) == 0 ||
1536        strncmp(basename, "MOD.", 4) == 0))
1537     return TRUE;
1538 #endif
1539
1540   return FALSE;
1541 }
1542
1543 boolean FileIsArtworkType(char *basename, int type)
1544 {
1545   if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(basename)) ||
1546       (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(basename)) ||
1547       (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(basename)))
1548     return TRUE;
1549
1550   return FALSE;
1551 }
1552
1553 /* ------------------------------------------------------------------------- */
1554 /* functions for loading artwork configuration information                   */
1555 /* ------------------------------------------------------------------------- */
1556
1557 /* This function checks if a string <s> of the format "string1, string2, ..."
1558    exactly contains a string <s_contained>. */
1559
1560 static boolean string_has_parameter(char *s, char *s_contained)
1561 {
1562   char *substring;
1563
1564   if (s == NULL || s_contained == NULL)
1565     return FALSE;
1566
1567   if (strlen(s_contained) > strlen(s))
1568     return FALSE;
1569
1570   if (strncmp(s, s_contained, strlen(s_contained)) == 0)
1571   {
1572     char next_char = s[strlen(s_contained)];
1573
1574     /* check if next character is delimiter or whitespace */
1575     return (next_char == ',' || next_char == '\0' ||
1576             next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
1577   }
1578
1579   /* check if string contains another parameter string after a comma */
1580   substring = strchr(s, ',');
1581   if (substring == NULL)        /* string does not contain a comma */
1582     return FALSE;
1583
1584   /* advance string pointer to next character after the comma */
1585   substring++;
1586
1587   /* skip potential whitespaces after the comma */
1588   while (*substring == ' ' || *substring == '\t')
1589     substring++;
1590
1591   return string_has_parameter(substring, s_contained);
1592 }
1593
1594 int get_parameter_value(char *token, char *value_raw, int type)
1595 {
1596   char *value = getStringToLower(value_raw);
1597   int result = 0;       /* probably a save default value */
1598
1599   if (strcmp(token, ".direction") == 0)
1600   {
1601     result = (strcmp(value, "left")  == 0 ? MV_LEFT :
1602               strcmp(value, "right") == 0 ? MV_RIGHT :
1603               strcmp(value, "up")    == 0 ? MV_UP :
1604               strcmp(value, "down")  == 0 ? MV_DOWN : MV_NO_MOVING);
1605   }
1606   else if (strcmp(token, ".anim_mode") == 0)
1607   {
1608     result = (string_has_parameter(value, "loop")      ? ANIM_LOOP :
1609               string_has_parameter(value, "linear")    ? ANIM_LINEAR :
1610               string_has_parameter(value, "pingpong")  ? ANIM_PINGPONG :
1611               string_has_parameter(value, "pingpong2") ? ANIM_PINGPONG2 :
1612               string_has_parameter(value, "random")    ? ANIM_RANDOM :
1613               ANIM_LOOP);
1614
1615     if (string_has_parameter(value, "reverse"))
1616       result |= ANIM_REVERSE;
1617   }
1618   else          /* generic parameter of type integer or boolean */
1619   {
1620     result = (strcmp(value, ARG_UNDEFINED) == 0 ? ARG_UNDEFINED_VALUE :
1621               type == TYPE_INTEGER ? get_integer_from_string(value) :
1622               type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
1623               ARG_UNDEFINED_VALUE);
1624   }
1625
1626   free(value);
1627
1628   return result;
1629 }
1630
1631 static void FreeCustomArtworkList(struct ArtworkListInfo *,
1632                                   struct ListNodeInfo ***, int *);
1633
1634 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
1635                                            struct ConfigInfo *suffix_list,
1636                                            char **ignore_tokens,
1637                                            int num_file_list_entries)
1638 {
1639   struct FileInfo *file_list;
1640   int num_file_list_entries_found = 0;
1641   int num_suffix_list_entries = 0;
1642   int list_pos;
1643   int i, j;
1644
1645   file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
1646
1647   for (i=0; suffix_list[i].token != NULL; i++)
1648     num_suffix_list_entries++;
1649
1650   /* always start with reliable default values */
1651   for (i=0; i<num_file_list_entries; i++)
1652   {
1653     file_list[i].token = NULL;
1654
1655     file_list[i].default_filename = NULL;
1656     file_list[i].filename = NULL;
1657
1658     if (num_suffix_list_entries > 0)
1659     {
1660       int parameter_array_size = num_suffix_list_entries * sizeof(char *);
1661
1662       file_list[i].default_parameter = checked_calloc(parameter_array_size);
1663       file_list[i].parameter = checked_calloc(parameter_array_size);
1664
1665       for (j=0; j<num_suffix_list_entries; j++)
1666       {
1667         setString(&file_list[i].default_parameter[j], suffix_list[j].value);
1668         setString(&file_list[i].parameter[j], suffix_list[j].value);
1669       }
1670     }
1671   }
1672
1673   list_pos = 0;
1674   for (i=0; config_list[i].token != NULL; i++)
1675   {
1676     int len_config_token = strlen(config_list[i].token);
1677     int len_config_value = strlen(config_list[i].value);
1678     boolean is_file_entry = TRUE;
1679
1680     for (j=0; suffix_list[j].token != NULL; j++)
1681     {
1682       int len_suffix = strlen(suffix_list[j].token);
1683
1684       if (len_suffix < len_config_token &&
1685           strcmp(&config_list[i].token[len_config_token - len_suffix],
1686                  suffix_list[j].token) == 0)
1687       {
1688         setString(&file_list[list_pos].default_parameter[j],
1689                   config_list[i].value);
1690
1691         is_file_entry = FALSE;
1692         break;
1693       }
1694     }
1695
1696     /* the following tokens are no file definitions, but other config tokens */
1697     for (j=0; ignore_tokens[j] != NULL; j++)
1698       if (strcmp(config_list[i].token, ignore_tokens[j]) == 0)
1699         is_file_entry = FALSE;
1700
1701     if (is_file_entry)
1702     {
1703       if (i > 0)
1704         list_pos++;
1705
1706       if (list_pos >= num_file_list_entries)
1707         break;
1708
1709       /* simple sanity check if this is really a file definition */
1710       if (strcmp(&config_list[i].value[len_config_value - 4], ".pcx") != 0 &&
1711           strcmp(&config_list[i].value[len_config_value - 4], ".wav") != 0 &&
1712           strcmp(config_list[i].value, UNDEFINED_FILENAME) != 0)
1713       {
1714         Error(ERR_RETURN, "Configuration directive '%s' -> '%s':",
1715               config_list[i].token, config_list[i].value);
1716         Error(ERR_EXIT, "This seems to be no valid definition -- please fix");
1717       }
1718
1719       file_list[list_pos].token = config_list[i].token;
1720       file_list[list_pos].default_filename = config_list[i].value;
1721     }
1722   }
1723
1724   num_file_list_entries_found = list_pos + 1;
1725   if (num_file_list_entries_found != num_file_list_entries)
1726   {
1727     Error(ERR_RETURN_LINE, "-");
1728     Error(ERR_RETURN, "inconsistant config list information:");
1729     Error(ERR_RETURN, "- should be:   %d (according to 'src/conf_gfx.h')",
1730           num_file_list_entries);
1731     Error(ERR_RETURN, "- found to be: %d (according to 'src/conf_gfx.c')",
1732           num_file_list_entries_found);
1733     Error(ERR_EXIT,   "please fix");
1734   }
1735
1736   return file_list;
1737 }
1738
1739 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
1740 {
1741   int len_token = strlen(token);
1742   int len_suffix = strlen(suffix);
1743
1744 #if 0
1745   if (IS_PARENT_PROCESS())
1746     printf(":::::::::: check '%s' for '%s' ::::::::::\n", token, suffix);
1747 #endif
1748
1749   if (start_pos < 0)    /* compare suffix from end of string */
1750     start_pos += len_token;
1751
1752   if (start_pos < 0 || start_pos + len_suffix > len_token)
1753     return FALSE;
1754
1755   if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
1756     return FALSE;
1757
1758   if (token[start_pos + len_suffix] == '\0')
1759     return TRUE;
1760
1761   if (token[start_pos + len_suffix] == '.')
1762     return TRUE;
1763
1764   return FALSE;
1765 }
1766
1767 #define KNOWN_TOKEN_VALUE       "[KNOWN_TOKEN]"
1768
1769 static void read_token_parameters(struct SetupFileList *setup_file_list,
1770                                   struct ConfigInfo *suffix_list,
1771                                   struct FileInfo *file_list_entry)
1772 {
1773   /* check for config token that is the base token without any suffixes */
1774   char *filename = getTokenValue(setup_file_list, file_list_entry->token);
1775   char *known_token_value = KNOWN_TOKEN_VALUE;
1776   int i;
1777
1778   if (filename != NULL)
1779   {
1780     setString(&file_list_entry->filename, filename);
1781
1782     /* when file definition found, set all parameters to default values */
1783     for (i=0; suffix_list[i].token != NULL; i++)
1784       setString(&file_list_entry->parameter[i], suffix_list[i].value);
1785
1786     file_list_entry->redefined = TRUE;
1787
1788     /* mark config file token as well known from default config */
1789     setTokenValue(setup_file_list, file_list_entry->token, known_token_value);
1790   }
1791   else
1792     setString(&file_list_entry->filename, file_list_entry->default_filename);
1793
1794   /* check for config tokens that can be build by base token and suffixes */
1795   for (i=0; suffix_list[i].token != NULL; i++)
1796   {
1797     char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
1798     char *value = getTokenValue(setup_file_list, token);
1799
1800     if (value != NULL)
1801     {
1802       setString(&file_list_entry->parameter[i], value);
1803
1804       /* mark config file token as well known from default config */
1805       setTokenValue(setup_file_list, token, known_token_value);
1806     }
1807
1808     free(token);
1809   }
1810 }
1811
1812 static void add_dynamic_file_list_entry(struct FileInfo **list,
1813                                         int *num_list_entries,
1814                                         struct SetupFileList *extra_file_list,
1815                                         struct ConfigInfo *suffix_list,
1816                                         int num_suffix_list_entries,
1817                                         char *token)
1818 {
1819   struct FileInfo *new_list_entry;
1820   int parameter_array_size = num_suffix_list_entries * sizeof(char *);
1821
1822 #if 0
1823   if (IS_PARENT_PROCESS())
1824     printf("===> found dynamic definition '%s'\n", token);
1825 #endif
1826
1827   (*num_list_entries)++;
1828   *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
1829   new_list_entry = &(*list)[*num_list_entries - 1];
1830
1831   new_list_entry->token = getStringCopy(token);
1832   new_list_entry->filename = NULL;
1833   new_list_entry->parameter = checked_calloc(parameter_array_size);
1834
1835   read_token_parameters(extra_file_list, suffix_list, new_list_entry);
1836 }
1837
1838 static void add_property_mapping(struct PropertyMapping **list,
1839                                  int *num_list_entries,
1840                                  int base_index, int ext1_index,
1841                                  int ext2_index, int ext3_index,
1842                                  int artwork_index)
1843 {
1844   struct PropertyMapping *new_list_entry;
1845
1846   (*num_list_entries)++;
1847   *list = checked_realloc(*list,
1848                           *num_list_entries * sizeof(struct PropertyMapping));
1849   new_list_entry = &(*list)[*num_list_entries - 1];
1850
1851   new_list_entry->base_index = base_index;
1852   new_list_entry->ext1_index = ext1_index;
1853   new_list_entry->ext2_index = ext2_index;
1854   new_list_entry->ext3_index = ext3_index;
1855
1856   new_list_entry->artwork_index = artwork_index;
1857 }
1858
1859 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
1860 {
1861   struct FileInfo *file_list = artwork_info->file_list;
1862   struct ConfigInfo *suffix_list = artwork_info->suffix_list;
1863   char **base_prefixes = artwork_info->base_prefixes;
1864   char **ext1_suffixes = artwork_info->ext1_suffixes;
1865   char **ext2_suffixes = artwork_info->ext2_suffixes;
1866   char **ext3_suffixes = artwork_info->ext3_suffixes;
1867   char **ignore_tokens = artwork_info->ignore_tokens;
1868   int num_file_list_entries = artwork_info->num_file_list_entries;
1869   int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
1870   int num_base_prefixes = artwork_info->num_base_prefixes;
1871   int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
1872   int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
1873   int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
1874   int num_ignore_tokens = artwork_info->num_ignore_tokens;
1875   char *filename = getCustomArtworkConfigFilename(artwork_info->type);
1876   struct SetupFileList *setup_file_list;
1877   struct SetupFileList *extra_file_list = NULL;
1878   struct SetupFileList *list;
1879   char *known_token_value = KNOWN_TOKEN_VALUE;
1880   int i, j, k, l;
1881
1882 #if 0
1883   printf("GOT CUSTOM ARTWORK CONFIG FILE '%s'\n", filename);
1884 #endif
1885
1886   /* always start with reliable default values */
1887   for (i=0; i<num_file_list_entries; i++)
1888   {
1889     setString(&file_list[i].filename, file_list[i].default_filename);
1890
1891     for (j=0; j<num_suffix_list_entries; j++)
1892       setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
1893
1894     file_list[i].redefined = FALSE;
1895   }
1896
1897   /* free previous dynamic artwork file array */
1898   if (artwork_info->dynamic_file_list != NULL)
1899   {
1900     for (i=0; i<artwork_info->num_dynamic_file_list_entries; i++)
1901     {
1902       free(artwork_info->dynamic_file_list[i].token);
1903       free(artwork_info->dynamic_file_list[i].filename);
1904       free(artwork_info->dynamic_file_list[i].parameter);
1905     }
1906
1907     free(artwork_info->dynamic_file_list);
1908     artwork_info->dynamic_file_list = NULL;
1909
1910     FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
1911                           &artwork_info->num_dynamic_file_list_entries);
1912   }
1913
1914   /* free previous property mapping */
1915   if (artwork_info->property_mapping != NULL)
1916   {
1917     free(artwork_info->property_mapping);
1918
1919     artwork_info->property_mapping = NULL;
1920     artwork_info->num_property_mapping_entries = 0;
1921   }
1922
1923   if (filename == NULL)
1924     return;
1925
1926   if ((setup_file_list = loadSetupFileList(filename)) == NULL)
1927     return;
1928
1929   /* read parameters for all known config file tokens */
1930   for (i=0; i<num_file_list_entries; i++)
1931     read_token_parameters(setup_file_list, suffix_list, &file_list[i]);
1932
1933   /* set all tokens that can be ignored here to "known" keyword */
1934   for (i=0; i < num_ignore_tokens; i++)
1935     setTokenValue(setup_file_list, ignore_tokens[i], known_token_value);
1936
1937   /* copy all unknown config file tokens to extra config list */
1938   for (list = setup_file_list; list != NULL; list = list->next)
1939   {
1940     if (strcmp(list->value, known_token_value) != 0)
1941     {
1942       if (extra_file_list == NULL)
1943         extra_file_list = newSetupFileList(list->token, list->value);
1944       else
1945         setTokenValue(extra_file_list, list->token, list->value);
1946     }
1947   }
1948
1949   /* at this point, we do not need the config file list anymore -- free it */
1950   freeSetupFileList(setup_file_list);
1951
1952   /* now try to determine valid, dynamically defined config tokens */
1953
1954   for (list = extra_file_list; list != NULL; list = list->next)
1955   {
1956     struct FileInfo **dynamic_file_list =
1957       &artwork_info->dynamic_file_list;
1958     int *num_dynamic_file_list_entries =
1959       &artwork_info->num_dynamic_file_list_entries;
1960     struct PropertyMapping **property_mapping =
1961       &artwork_info->property_mapping;
1962     int *num_property_mapping_entries =
1963       &artwork_info->num_property_mapping_entries;
1964     int current_summarized_file_list_entry =
1965       artwork_info->num_file_list_entries +
1966       artwork_info->num_dynamic_file_list_entries;
1967     char *token = list->token;
1968     int len_token = strlen(token);
1969     int start_pos;
1970     boolean base_prefix_found = FALSE;
1971     boolean parameter_suffix_found = FALSE;
1972
1973     /* skip all parameter definitions (handled by read_token_parameters()) */
1974     for (i=0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
1975     {
1976       int len_suffix = strlen(suffix_list[i].token);
1977
1978       if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
1979         parameter_suffix_found = TRUE;
1980     }
1981
1982 #if 0
1983     if (IS_PARENT_PROCESS())
1984     {
1985       if (parameter_suffix_found)
1986         printf("---> skipping token '%s' (parameter token)\n", token);
1987       else
1988         printf("---> examining token '%s': search prefix ...\n", token);
1989     }
1990 #endif
1991
1992     if (parameter_suffix_found)
1993       continue;
1994
1995     /* ---------- step 0: search for matching base prefix ---------- */
1996
1997     start_pos = 0;
1998     for (i=0; i<num_base_prefixes && !base_prefix_found; i++)
1999     {
2000       char *base_prefix = base_prefixes[i];
2001       int len_base_prefix = strlen(base_prefix);
2002       boolean ext1_suffix_found = FALSE;
2003       boolean ext2_suffix_found = FALSE;
2004       boolean ext3_suffix_found = FALSE;
2005       boolean exact_match = FALSE;
2006       int base_index = -1;
2007       int ext1_index = -1;
2008       int ext2_index = -1;
2009       int ext3_index = -1;
2010
2011       base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
2012
2013       if (!base_prefix_found)
2014         continue;
2015
2016       base_index = i;
2017
2018       if (start_pos + len_base_prefix == len_token)     /* exact match */
2019       {
2020         exact_match = TRUE;
2021
2022         add_dynamic_file_list_entry(dynamic_file_list,
2023                                     num_dynamic_file_list_entries,
2024                                     extra_file_list,
2025                                     suffix_list,
2026                                     num_suffix_list_entries,
2027                                     token);
2028         add_property_mapping(property_mapping,
2029                              num_property_mapping_entries,
2030                              base_index, -1, -1, -1,
2031                              current_summarized_file_list_entry);
2032         continue;
2033       }
2034
2035 #if 0
2036       if (IS_PARENT_PROCESS())
2037         printf("---> examining token '%s': search 1st suffix ...\n", token);
2038 #endif
2039
2040       /* ---------- step 1: search for matching first suffix ---------- */
2041
2042       start_pos += len_base_prefix;
2043       for (j=0; j<num_ext1_suffixes && !ext1_suffix_found; j++)
2044       {
2045         char *ext1_suffix = ext1_suffixes[j];
2046         int len_ext1_suffix = strlen(ext1_suffix);
2047
2048         ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
2049
2050         if (!ext1_suffix_found)
2051           continue;
2052
2053         ext1_index = j;
2054
2055         if (start_pos + len_ext1_suffix == len_token)   /* exact match */
2056         {
2057           exact_match = TRUE;
2058
2059           add_dynamic_file_list_entry(dynamic_file_list,
2060                                       num_dynamic_file_list_entries,
2061                                       extra_file_list,
2062                                       suffix_list,
2063                                       num_suffix_list_entries,
2064                                       token);
2065           add_property_mapping(property_mapping,
2066                                num_property_mapping_entries,
2067                                base_index, ext1_index, -1, -1,
2068                                current_summarized_file_list_entry);
2069           continue;
2070         }
2071
2072         start_pos += len_ext1_suffix;
2073       }
2074
2075       if (exact_match)
2076         break;
2077
2078 #if 0
2079       if (IS_PARENT_PROCESS())
2080         printf("---> examining token '%s': search 2nd suffix ...\n", token);
2081 #endif
2082
2083       /* ---------- step 2: search for matching second suffix ---------- */
2084
2085       for (k=0; k<num_ext2_suffixes && !ext2_suffix_found; k++)
2086       {
2087         char *ext2_suffix = ext2_suffixes[k];
2088         int len_ext2_suffix = strlen(ext2_suffix);
2089
2090         ext2_suffix_found = token_suffix_match(token, ext2_suffix,start_pos);
2091
2092         if (!ext2_suffix_found)
2093           continue;
2094
2095         ext2_index = k;
2096
2097         if (start_pos + len_ext2_suffix == len_token)   /* exact match */
2098         {
2099           exact_match = TRUE;
2100
2101           add_dynamic_file_list_entry(dynamic_file_list,
2102                                       num_dynamic_file_list_entries,
2103                                       extra_file_list,
2104                                       suffix_list,
2105                                       num_suffix_list_entries,
2106                                       token);
2107           add_property_mapping(property_mapping,
2108                                num_property_mapping_entries,
2109                                base_index, ext1_index, ext2_index, -1,
2110                                current_summarized_file_list_entry);
2111           continue;
2112         }
2113
2114         start_pos += len_ext2_suffix;
2115       }
2116
2117       if (exact_match)
2118         break;
2119
2120 #if 0
2121       if (IS_PARENT_PROCESS())
2122         printf("---> examining token '%s': search 3rd suffix ...\n",token);
2123 #endif
2124
2125       /* ---------- step 3: search for matching third suffix ---------- */
2126
2127       for (l=0; l<num_ext3_suffixes && !ext3_suffix_found; l++)
2128       {
2129         char *ext3_suffix = ext3_suffixes[l];
2130         int len_ext3_suffix = strlen(ext3_suffix);
2131
2132         ext3_suffix_found =token_suffix_match(token,ext3_suffix,start_pos);
2133
2134         if (!ext3_suffix_found)
2135           continue;
2136
2137         ext3_index = l;
2138
2139         if (start_pos + len_ext3_suffix == len_token) /* exact match */
2140         {
2141           exact_match = TRUE;
2142
2143           add_dynamic_file_list_entry(dynamic_file_list,
2144                                       num_dynamic_file_list_entries,
2145                                       extra_file_list,
2146                                       suffix_list,
2147                                       num_suffix_list_entries,
2148                                       token);
2149           add_property_mapping(property_mapping,
2150                                num_property_mapping_entries,
2151                                base_index, ext1_index, ext2_index, ext3_index,
2152                                current_summarized_file_list_entry);
2153           continue;
2154         }
2155       }
2156     }
2157   }
2158
2159   if (artwork_info->num_dynamic_file_list_entries > 0)
2160   {
2161     artwork_info->dynamic_artwork_list =
2162       checked_calloc(artwork_info->num_dynamic_file_list_entries *
2163                      artwork_info->sizeof_artwork_list_entry);
2164   }
2165
2166   if (extra_file_list != NULL && options.verbose && IS_PARENT_PROCESS())
2167   {
2168     boolean dynamic_tokens_found = FALSE;
2169     boolean unknown_tokens_found = FALSE;
2170
2171     for (list = extra_file_list; list != NULL; list = list->next)
2172     {
2173       if (strcmp(list->value, known_token_value) == 0)
2174         dynamic_tokens_found = TRUE;
2175       else
2176         unknown_tokens_found = TRUE;
2177     }
2178
2179 #if DEBUG
2180     if (dynamic_tokens_found)
2181     {
2182       Error(ERR_RETURN_LINE, "-");
2183       Error(ERR_RETURN, "dynamic token(s) found:");
2184
2185       for (list = extra_file_list; list != NULL; list = list->next)
2186         if (strcmp(list->value, known_token_value) == 0)
2187           Error(ERR_RETURN, "- dynamic token: '%s'", list->token);
2188
2189       Error(ERR_RETURN_LINE, "-");
2190     }
2191 #endif
2192
2193     if (unknown_tokens_found)
2194     {
2195       Error(ERR_RETURN_LINE, "-");
2196       Error(ERR_RETURN, "warning: unknown token(s) found in config file:");
2197       Error(ERR_RETURN, "- config file: '%s'", filename);
2198
2199       for (list = extra_file_list; list != NULL; list = list->next)
2200         if (strcmp(list->value, known_token_value) != 0)
2201           Error(ERR_RETURN, "- unknown token: '%s'", list->token);
2202
2203       Error(ERR_RETURN_LINE, "-");
2204     }
2205   }
2206
2207   freeSetupFileList(extra_file_list);
2208
2209 #if 0
2210   for (i=0; i<num_file_list_entries; i++)
2211   {
2212     printf("'%s' ", file_list[i].token);
2213     if (file_list[i].filename)
2214       printf("-> '%s'\n", file_list[i].filename);
2215     else
2216       printf("-> UNDEFINED [-> '%s']\n", file_list[i].default_filename);
2217   }
2218 #endif
2219 }
2220
2221 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
2222                                    struct ListNodeInfo **listnode)
2223 {
2224   if (*listnode)
2225   {
2226     char *filename = (*listnode)->source_filename;
2227
2228 #if 0
2229     printf("[decrementing reference counter of artwork '%s']\n", filename);
2230 #endif
2231
2232     if (--(*listnode)->num_references <= 0)
2233     {
2234 #if 0
2235       printf("[deleting artwork '%s']\n", filename);
2236 #endif
2237
2238       deleteNodeFromList(&artwork_info->content_list, filename,
2239                          artwork_info->free_artwork);
2240     }
2241
2242     *listnode = NULL;
2243   }
2244 }
2245
2246 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
2247                                     struct ListNodeInfo **listnode,
2248                                     char *basename)
2249 {
2250   char *init_text[] =
2251   { "",
2252     "Loading graphics:",
2253     "Loading sounds:",
2254     "Loading music:"
2255   };
2256
2257   ListNode *node;
2258   char *filename = getCustomArtworkFilename(basename, artwork_info->type);
2259
2260   if (filename == NULL)
2261   {
2262     int error_mode = ERR_WARN;
2263
2264     /* we can get away without sounds and music, but not without graphics */
2265     if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
2266       error_mode = ERR_EXIT;
2267
2268     Error(error_mode, "cannot find artwork file '%s'", basename);
2269     return;
2270   }
2271
2272   /* check if the old and the new artwork file are the same */
2273   if (*listnode && strcmp((*listnode)->source_filename, filename) == 0)
2274   {
2275     /* The old and new artwork are the same (have the same filename and path).
2276        This usually means that this artwork does not exist in this artwork set
2277        and a fallback to the existing artwork is done. */
2278
2279 #if 0
2280     printf("[artwork '%s' already exists (same list entry)]\n", filename);
2281 #endif
2282
2283     return;
2284   }
2285
2286   /* delete existing artwork file entry */
2287   deleteArtworkListEntry(artwork_info, listnode);
2288
2289   /* check if the new artwork file already exists in the list of artworks */
2290   if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
2291   {
2292 #if 0
2293       printf("[artwork '%s' already exists (other list entry)]\n", filename);
2294 #endif
2295
2296       *listnode = (struct ListNodeInfo *)node->content;
2297       (*listnode)->num_references++;
2298
2299       return;
2300   }
2301
2302   DrawInitText(init_text[artwork_info->type], 120, FC_GREEN);
2303   DrawInitText(basename, 150, FC_YELLOW);
2304
2305   if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
2306   {
2307 #if 0
2308       printf("[adding new artwork '%s']\n", filename);
2309 #endif
2310
2311     (*listnode)->num_references = 1;
2312     addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
2313                   *listnode);
2314   }
2315   else
2316   {
2317     int error_mode = ERR_WARN;
2318
2319     /* we can get away without sounds and music, but not without graphics */
2320     if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
2321       error_mode = ERR_EXIT;
2322
2323     Error(error_mode, "cannot load artwork file '%s'", basename);
2324     return;
2325   }
2326 }
2327
2328 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
2329                               struct ListNodeInfo **listnode,
2330                               char *basename)
2331 {
2332 #if 0
2333   printf("GOT CUSTOM ARTWORK FILE '%s'\n", filename);
2334 #endif
2335
2336   if (strcmp(basename, UNDEFINED_FILENAME) == 0)
2337   {
2338     deleteArtworkListEntry(artwork_info, listnode);
2339     return;
2340   }
2341
2342   replaceArtworkListEntry(artwork_info, listnode, basename);
2343 }
2344
2345 static void LoadArtworkToList(struct ArtworkListInfo *artwork_info,
2346                               struct ListNodeInfo **listnode,
2347                               char *basename, int list_pos)
2348 {
2349 #if 0
2350   if (artwork_info->artwork_list == NULL ||
2351       list_pos >= artwork_info->num_file_list_entries)
2352     return;
2353 #endif
2354
2355 #if 0
2356   printf("loading artwork '%s' ...  [%d]\n",
2357          basename, getNumNodes(artwork_info->content_list));
2358 #endif
2359
2360 #if 1
2361   LoadCustomArtwork(artwork_info, listnode, basename);
2362 #else
2363   LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[list_pos],
2364                     basename);
2365 #endif
2366
2367 #if 0
2368   printf("loading artwork '%s' done [%d]\n",
2369          basename, getNumNodes(artwork_info->content_list));
2370 #endif
2371 }
2372
2373 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
2374 {
2375   struct FileInfo *file_list = artwork_info->file_list;
2376   struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
2377   int num_file_list_entries = artwork_info->num_file_list_entries;
2378   int num_dynamic_file_list_entries =
2379     artwork_info->num_dynamic_file_list_entries;
2380   int i;
2381
2382 #if 0
2383   printf("DEBUG: reloading %d static artwork files ...\n",
2384          num_file_list_entries);
2385 #endif
2386
2387   for(i=0; i<num_file_list_entries; i++)
2388     LoadArtworkToList(artwork_info, &artwork_info->artwork_list[i],
2389                       file_list[i].filename, i);
2390
2391 #if 0
2392   printf("DEBUG: reloading %d dynamic artwork files ...\n",
2393          num_dynamic_file_list_entries);
2394 #endif
2395
2396   for(i=0; i<num_dynamic_file_list_entries; i++)
2397     LoadArtworkToList(artwork_info, &artwork_info->dynamic_artwork_list[i],
2398                       dynamic_file_list[i].filename, i);
2399
2400 #if 0
2401   dumpList(artwork_info->content_list);
2402 #endif
2403 }
2404
2405 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
2406                                   struct ListNodeInfo ***list,
2407                                   int *num_list_entries)
2408 {
2409   int i;
2410
2411   if (*list == NULL)
2412     return;
2413
2414   for(i=0; i<*num_list_entries; i++)
2415     deleteArtworkListEntry(artwork_info, &(*list)[i]);
2416   free(*list);
2417
2418   *list = NULL;
2419   *num_list_entries = 0;
2420 }
2421
2422 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
2423 {
2424   if (artwork_info == NULL)
2425     return;
2426
2427 #if 0
2428   printf("%s: FREEING ARTWORK ...\n",
2429          IS_CHILD_PROCESS() ? "CHILD" : "PARENT");
2430 #endif
2431
2432   FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
2433                         &artwork_info->num_file_list_entries);
2434
2435   FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
2436                         &artwork_info->num_dynamic_file_list_entries);
2437
2438 #if 0
2439   printf("%s: FREEING ARTWORK -- DONE\n",
2440          IS_CHILD_PROCESS() ? "CHILD" : "PARENT");
2441 #endif
2442 }
2443
2444
2445 /* ------------------------------------------------------------------------- */
2446 /* functions only needed for non-Unix (non-command-line) systems             */
2447 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt")    */
2448 /* ------------------------------------------------------------------------- */
2449
2450 #if defined(PLATFORM_MSDOS)
2451
2452 #define ERROR_FILENAME          "stderr.txt"
2453
2454 void initErrorFile()
2455 {
2456   unlink(ERROR_FILENAME);
2457 }
2458
2459 FILE *openErrorFile()
2460 {
2461   return fopen(ERROR_FILENAME, MODE_APPEND);
2462 }
2463
2464 void dumpErrorFile()
2465 {
2466   FILE *error_file = fopen(ERROR_FILENAME, MODE_READ);
2467
2468   if (error_file != NULL)
2469   {
2470     while (!feof(error_file))
2471       fputc(fgetc(error_file), stderr);
2472
2473     fclose(error_file);
2474   }
2475 }
2476 #endif
2477
2478
2479 /* ------------------------------------------------------------------------- */
2480 /* the following is only for debugging purpose and normally not used         */
2481 /* ------------------------------------------------------------------------- */
2482
2483 #define DEBUG_NUM_TIMESTAMPS    3
2484
2485 void debug_print_timestamp(int counter_nr, char *message)
2486 {
2487   static long counter[DEBUG_NUM_TIMESTAMPS][2];
2488
2489   if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
2490     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
2491
2492   counter[counter_nr][0] = Counter();
2493
2494   if (message)
2495     printf("%s %.2f seconds\n", message,
2496            (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
2497
2498   counter[counter_nr][1] = Counter();
2499 }
2500
2501 void debug_print_parent_only(char *format, ...)
2502 {
2503   if (!IS_PARENT_PROCESS())
2504     return;
2505
2506   if (format)
2507   {
2508     va_list ap;
2509
2510     va_start(ap, format);
2511     vprintf(format, ap);
2512     va_end(ap);
2513
2514     printf("\n");
2515   }
2516 }