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