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