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