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