rnd-20020601-1-src
[rocksndiamonds.git] / src / libgame / misc.c
1 /***********************************************************
2 * Artsoft Retro-Game Library                               *
3 *----------------------------------------------------------*
4 * (c) 1994-2001 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
33
34 #if defined(PLATFORM_MSDOS)
35 volatile unsigned long counter = 0;
36
37 void increment_counter()
38 {
39   counter++;
40 }
41
42 END_OF_FUNCTION(increment_counter);
43 #endif
44
45
46 /* maximal allowed length of a command line option */
47 #define MAX_OPTION_LEN          256
48
49 #ifdef TARGET_SDL
50 static unsigned long mainCounter(int mode)
51 {
52   static unsigned long base_ms = 0;
53   unsigned long current_ms;
54   unsigned long counter_ms;
55
56   current_ms = SDL_GetTicks();
57
58   /* reset base time in case of counter initializing or wrap-around */
59   if (mode == INIT_COUNTER || current_ms < base_ms)
60     base_ms = current_ms;
61
62   counter_ms = current_ms - base_ms;
63
64   return counter_ms;            /* return milliseconds since last init */
65 }
66
67 #else /* !TARGET_SDL */
68
69 #if defined(PLATFORM_UNIX)
70 static unsigned long mainCounter(int mode)
71 {
72   static struct timeval base_time = { 0, 0 };
73   struct timeval current_time;
74   unsigned long counter_ms;
75
76   gettimeofday(&current_time, NULL);
77
78   /* reset base time in case of counter initializing or wrap-around */
79   if (mode == INIT_COUNTER || current_time.tv_sec < base_time.tv_sec)
80     base_time = current_time;
81
82   counter_ms = (current_time.tv_sec  - base_time.tv_sec)  * 1000
83              + (current_time.tv_usec - base_time.tv_usec) / 1000;
84
85   return counter_ms;            /* return milliseconds since last init */
86 }
87 #endif /* PLATFORM_UNIX */
88 #endif /* !TARGET_SDL */
89
90 void InitCounter()              /* set counter back to zero */
91 {
92 #if !defined(PLATFORM_MSDOS)
93   mainCounter(INIT_COUNTER);
94 #else
95   LOCK_VARIABLE(counter);
96   LOCK_FUNCTION(increment_counter);
97   install_int_ex(increment_counter, BPS_TO_TIMER(100));
98 #endif
99 }
100
101 unsigned long Counter() /* get milliseconds since last call of InitCounter() */
102 {
103 #if !defined(PLATFORM_MSDOS)
104   return mainCounter(READ_COUNTER);
105 #else
106   return (counter * 10);
107 #endif
108 }
109
110 static void sleep_milliseconds(unsigned long milliseconds_delay)
111 {
112   boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
113
114 #if 0
115 #if defined(PLATFORM_MSDOS)
116   /* don't use select() to perform waiting operations under DOS
117      environment; always use a busy loop for waiting instead */
118   do_busy_waiting = TRUE;
119 #endif
120 #endif
121
122   if (do_busy_waiting)
123   {
124     /* we want to wait only a few ms -- if we assume that we have a
125        kernel timer resolution of 10 ms, we would wait far to long;
126        therefore it's better to do a short interval of busy waiting
127        to get our sleeping time more accurate */
128
129     unsigned long base_counter = Counter(), actual_counter = Counter();
130
131     while (actual_counter < base_counter + milliseconds_delay &&
132            actual_counter >= base_counter)
133       actual_counter = Counter();
134   }
135   else
136   {
137 #if defined(TARGET_SDL)
138     SDL_Delay(milliseconds_delay);
139 #elif defined(TARGET_ALLEGRO)
140     rest(milliseconds_delay);
141 #else
142     struct timeval delay;
143
144     delay.tv_sec  = milliseconds_delay / 1000;
145     delay.tv_usec = 1000 * (milliseconds_delay % 1000);
146
147     if (select(0, NULL, NULL, NULL, &delay) != 0)
148       Error(ERR_WARN, "sleep_milliseconds(): select() failed");
149 #endif
150   }
151 }
152
153 void Delay(unsigned long delay) /* Sleep specified number of milliseconds */
154 {
155   sleep_milliseconds(delay);
156 }
157
158 boolean FrameReached(unsigned long *frame_counter_var,
159                      unsigned long frame_delay)
160 {
161   unsigned long actual_frame_counter = FrameCounter;
162
163   if (actual_frame_counter < *frame_counter_var + frame_delay &&
164       actual_frame_counter >= *frame_counter_var)
165     return FALSE;
166
167   *frame_counter_var = actual_frame_counter;
168
169   return TRUE;
170 }
171
172 boolean DelayReached(unsigned long *counter_var,
173                      unsigned long delay)
174 {
175   unsigned long actual_counter = Counter();
176
177   if (actual_counter < *counter_var + delay &&
178       actual_counter >= *counter_var)
179     return FALSE;
180
181   *counter_var = actual_counter;
182
183   return TRUE;
184 }
185
186 void WaitUntilDelayReached(unsigned long *counter_var, unsigned long delay)
187 {
188   unsigned long actual_counter;
189
190   while(1)
191   {
192     actual_counter = Counter();
193
194     if (actual_counter < *counter_var + delay &&
195         actual_counter >= *counter_var)
196       sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
197     else
198       break;
199   }
200
201   *counter_var = actual_counter;
202 }
203
204 /* int2str() returns a number converted to a string;
205    the used memory is static, but will be overwritten by later calls,
206    so if you want to save the result, copy it to a private string buffer;
207    there can be 10 local calls of int2str() without buffering the result --
208    the 11th call will then destroy the result from the first call and so on.
209 */
210
211 char *int2str(int number, int size)
212 {
213   static char shift_array[10][40];
214   static int shift_counter = 0;
215   char *s = shift_array[shift_counter];
216
217   shift_counter = (shift_counter + 1) % 10;
218
219   if (size > 20)
220     size = 20;
221
222   if (size)
223   {
224     sprintf(s, "                    %09d", number);
225     return &s[strlen(s) - size];
226   }
227   else
228   {
229     sprintf(s, "%d", number);
230     return s;
231   }
232 }
233
234 unsigned int SimpleRND(unsigned int max)
235 {
236 #if defined(TARGET_SDL)
237   static unsigned long root = 654321;
238   unsigned long current_ms;
239
240   current_ms = SDL_GetTicks();
241   root = root * 4253261 + current_ms;
242   return (root % max);
243 #else
244   static unsigned long root = 654321;
245   struct timeval current_time;
246
247   gettimeofday(&current_time, NULL);
248   root = root * 4253261 + current_time.tv_sec + current_time.tv_usec;
249   return (root % max);
250 #endif
251 }
252
253 #ifdef DEBUG
254 static unsigned int last_RND_value = 0;
255
256 unsigned int last_RND()
257 {
258   return last_RND_value;
259 }
260 #endif
261
262 unsigned int RND(unsigned int max)
263 {
264 #ifdef DEBUG
265   return (last_RND_value = random_linux_libc() % max);
266 #else
267   return (random_linux_libc() % max);
268 #endif
269 }
270
271 unsigned int InitRND(long seed)
272 {
273 #if defined(TARGET_SDL)
274   unsigned long current_ms;
275
276   if (seed == NEW_RANDOMIZE)
277   {
278     current_ms = SDL_GetTicks();
279     srandom_linux_libc((unsigned int) current_ms);
280     return (unsigned int) current_ms;
281   }
282   else
283   {
284     srandom_linux_libc((unsigned int) seed);
285     return (unsigned int) seed;
286   }
287 #else
288   struct timeval current_time;
289
290   if (seed == NEW_RANDOMIZE)
291   {
292     gettimeofday(&current_time, NULL);
293     srandom_linux_libc((unsigned int) current_time.tv_usec);
294     return (unsigned int) current_time.tv_usec;
295   }
296   else
297   {
298     srandom_linux_libc((unsigned int) seed);
299     return (unsigned int) seed;
300   }
301 #endif
302 }
303
304 char *getLoginName()
305 {
306 #if defined(PLATFORM_WIN32)
307   return ANONYMOUS_NAME;
308 #else
309   struct passwd *pwd;
310
311   if ((pwd = getpwuid(getuid())) == NULL)
312     return ANONYMOUS_NAME;
313   else
314     return pwd->pw_name;
315 #endif
316 }
317
318 char *getRealName()
319 {
320 #if defined(PLATFORM_UNIX)
321   struct passwd *pwd;
322
323   if ((pwd = getpwuid(getuid())) == NULL || strlen(pwd->pw_gecos) == 0)
324     return ANONYMOUS_NAME;
325   else
326   {
327     static char real_name[1024];
328     char *from_ptr = pwd->pw_gecos, *to_ptr = real_name;
329
330     if (strchr(pwd->pw_gecos, 'ß') == NULL)
331       return pwd->pw_gecos;
332
333     /* the user's real name contains a 'ß' character (german sharp s),
334        which has no equivalent in upper case letters (which our fonts use) */
335     while (*from_ptr != '\0' && (long)(to_ptr - real_name) < 1024 - 2)
336     {
337       if (*from_ptr != 'ß')
338         *to_ptr++ = *from_ptr++;
339       else
340       {
341         from_ptr++;
342         *to_ptr++ = 's';
343         *to_ptr++ = 's';
344       }
345     }
346     *to_ptr = '\0';
347
348     return real_name;
349   }
350 #else /* !PLATFORM_UNIX */
351   return ANONYMOUS_NAME;
352 #endif
353 }
354
355 char *getHomeDir()
356 {
357 #if defined(PLATFORM_UNIX)
358   static char *home_dir = NULL;
359
360   if (!home_dir)
361   {
362     if (!(home_dir = getenv("HOME")))
363     {
364       struct passwd *pwd;
365
366       if ((pwd = getpwuid(getuid())))
367         home_dir = pwd->pw_dir;
368       else
369         home_dir = ".";
370     }
371   }
372
373   return home_dir;
374 #else
375   return ".";
376 #endif
377 }
378
379 char *getPath2(char *path1, char *path2)
380 {
381   char *complete_path = checked_malloc(strlen(path1) + 1 +
382                                        strlen(path2) + 1);
383
384   sprintf(complete_path, "%s/%s", path1, path2);
385   return complete_path;
386 }
387
388 char *getPath3(char *path1, char *path2, char *path3)
389 {
390   char *complete_path = checked_malloc(strlen(path1) + 1 +
391                                        strlen(path2) + 1 +
392                                        strlen(path3) + 1);
393
394   sprintf(complete_path, "%s/%s/%s", path1, path2, path3);
395   return complete_path;
396 }
397
398 char *getStringCopy(char *s)
399 {
400   char *s_copy;
401
402   if (s == NULL)
403     return NULL;
404
405   s_copy = checked_malloc(strlen(s) + 1);
406
407   strcpy(s_copy, s);
408   return s_copy;
409 }
410
411 char *getStringToLower(char *s)
412 {
413   char *s_copy = checked_malloc(strlen(s) + 1);
414   char *s_ptr = s_copy;
415
416   while (*s)
417     *s_ptr++ = tolower(*s++);
418   *s_ptr = '\0';
419
420   return s_copy;
421 }
422
423 void GetOptions(char *argv[])
424 {
425   char **options_left = &argv[1];
426
427   /* initialize global program options */
428   options.display_name = NULL;
429   options.server_host = NULL;
430   options.server_port = 0;
431   options.ro_base_directory = RO_BASE_PATH;
432   options.rw_base_directory = RW_BASE_PATH;
433   options.level_directory = RO_BASE_PATH "/" LEVELS_DIRECTORY;
434   options.graphics_directory = RO_BASE_PATH "/" GRAPHICS_DIRECTORY;
435   options.sounds_directory = RO_BASE_PATH "/" SOUNDS_DIRECTORY;
436   options.music_directory = RO_BASE_PATH "/" MUSIC_DIRECTORY;
437   options.serveronly = FALSE;
438   options.network = FALSE;
439   options.verbose = FALSE;
440   options.debug = FALSE;
441   options.debug_command = NULL;
442
443   while (*options_left)
444   {
445     char option_str[MAX_OPTION_LEN];
446     char *option = options_left[0];
447     char *next_option = options_left[1];
448     char *option_arg = NULL;
449     int option_len = strlen(option);
450
451     if (option_len >= MAX_OPTION_LEN)
452       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
453
454     strcpy(option_str, option);                 /* copy argument into buffer */
455     option = option_str;
456
457     if (strcmp(option, "--") == 0)              /* stop scanning arguments */
458       break;
459
460     if (strncmp(option, "--", 2) == 0)          /* treat '--' like '-' */
461       option++;
462
463     option_arg = strchr(option, '=');
464     if (option_arg == NULL)                     /* no '=' in option */
465       option_arg = next_option;
466     else
467     {
468       *option_arg++ = '\0';                     /* cut argument from option */
469       if (*option_arg == '\0')                  /* no argument after '=' */
470         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
471     }
472
473     option_len = strlen(option);
474
475     if (strcmp(option, "-") == 0)
476       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
477     else if (strncmp(option, "-help", option_len) == 0)
478     {
479       printf("Usage: %s [options] [<server host> [<server port>]]\n"
480              "Options:\n"
481              "  -d, --display <host>[:<scr>]  X server display\n"
482              "  -b, --basepath <directory>    alternative base directory\n"
483              "  -l, --level <directory>       alternative level directory\n"
484              "  -g, --graphics <directory>    alternative graphics directory\n"
485              "  -s, --sounds <directory>      alternative sounds directory\n"
486              "  -m, --music <directory>       alternative music directory\n"
487              "  -n, --network                 network multiplayer game\n"
488              "      --serveronly              only start network server\n"
489              "  -v, --verbose                 verbose mode\n"
490              "      --debug                   display debugging information\n",
491              program.command_basename);
492
493       if (options.debug)
494         printf("      --debug-command <command> execute special command\n");
495
496       exit(0);
497     }
498     else if (strncmp(option, "-display", option_len) == 0)
499     {
500       if (option_arg == NULL)
501         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
502
503       options.display_name = option_arg;
504       if (option_arg == next_option)
505         options_left++;
506     }
507     else if (strncmp(option, "-basepath", option_len) == 0)
508     {
509       if (option_arg == NULL)
510         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
511
512       /* this should be extended to separate options for ro and rw data */
513       options.ro_base_directory = option_arg;
514       options.rw_base_directory = option_arg;
515       if (option_arg == next_option)
516         options_left++;
517
518       /* adjust path for level directory accordingly */
519       options.level_directory =
520         getPath2(options.ro_base_directory, LEVELS_DIRECTORY);
521     }
522     else if (strncmp(option, "-levels", option_len) == 0)
523     {
524       if (option_arg == NULL)
525         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
526
527       options.level_directory = option_arg;
528       if (option_arg == next_option)
529         options_left++;
530     }
531     else if (strncmp(option, "-graphics", option_len) == 0)
532     {
533       if (option_arg == NULL)
534         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
535
536       options.graphics_directory = option_arg;
537       if (option_arg == next_option)
538         options_left++;
539     }
540     else if (strncmp(option, "-sounds", option_len) == 0)
541     {
542       if (option_arg == NULL)
543         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
544
545       options.sounds_directory = option_arg;
546       if (option_arg == next_option)
547         options_left++;
548     }
549     else if (strncmp(option, "-music", option_len) == 0)
550     {
551       if (option_arg == NULL)
552         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
553
554       options.music_directory = option_arg;
555       if (option_arg == next_option)
556         options_left++;
557     }
558     else if (strncmp(option, "-network", option_len) == 0)
559     {
560       options.network = TRUE;
561     }
562     else if (strncmp(option, "-serveronly", option_len) == 0)
563     {
564       options.serveronly = TRUE;
565     }
566     else if (strncmp(option, "-verbose", option_len) == 0)
567     {
568       options.verbose = TRUE;
569     }
570     else if (strncmp(option, "-debug", option_len) == 0)
571     {
572       options.debug = TRUE;
573     }
574     else if (strncmp(option, "-debug-command", option_len) == 0)
575     {
576       if (option_arg == NULL)
577         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
578
579       options.debug_command = option_arg;
580       if (option_arg == next_option)
581         options_left++;
582     }
583     else if (*option == '-')
584     {
585       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
586     }
587     else if (options.server_host == NULL)
588     {
589       options.server_host = *options_left;
590     }
591     else if (options.server_port == 0)
592     {
593       options.server_port = atoi(*options_left);
594       if (options.server_port < 1024)
595         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
596     }
597     else
598       Error(ERR_EXIT_HELP, "too many arguments");
599
600     options_left++;
601   }
602 }
603
604 /* used by SetError() and GetError() to store internal error messages */
605 static char internal_error[1024];       /* this is bad */
606
607 void SetError(char *format, ...)
608 {
609   va_list ap;
610
611   va_start(ap, format);
612   vsprintf(internal_error, format, ap);
613   va_end(ap);
614 }
615
616 char *GetError()
617 {
618   return internal_error;
619 }
620
621 void Error(int mode, char *format, ...)
622 {
623   char *process_name = "";
624   FILE *error = stderr;
625   char *newline = "\n";
626
627   /* display warnings only when running in verbose mode */
628   if (mode & ERR_WARN && !options.verbose)
629     return;
630
631 #if !defined(PLATFORM_UNIX)
632   newline = "\r\n";
633
634   if ((error = openErrorFile()) == NULL)
635   {
636     printf("Cannot write to error output file!%s", newline);
637     program.exit_function(1);
638   }
639 #endif
640
641   if (mode & ERR_SOUND_SERVER)
642     process_name = " sound server";
643   else if (mode & ERR_NETWORK_SERVER)
644     process_name = " network server";
645   else if (mode & ERR_NETWORK_CLIENT)
646     process_name = " network client **";
647
648   if (format)
649   {
650     va_list ap;
651
652     fprintf(error, "%s%s: ", program.command_basename, process_name);
653
654     if (mode & ERR_WARN)
655       fprintf(error, "warning: ");
656
657     va_start(ap, format);
658     vfprintf(error, format, ap);
659     va_end(ap);
660   
661     fprintf(error, "%s", newline);
662   }
663   
664   if (mode & ERR_HELP)
665     fprintf(error, "%s: Try option '--help' for more information.%s",
666             program.command_basename, newline);
667
668   if (mode & ERR_EXIT)
669     fprintf(error, "%s%s: aborting%s",
670             program.command_basename, process_name, newline);
671
672   if (error != stderr)
673     fclose(error);
674
675   if (mode & ERR_EXIT)
676   {
677     if (mode & ERR_FROM_SERVER)
678       exit(1);                          /* child process: normal exit */
679     else
680       program.exit_function(1);         /* main process: clean up stuff */
681   }
682 }
683
684 void *checked_malloc(unsigned long size)
685 {
686   void *ptr;
687
688   ptr = malloc(size);
689
690   if (ptr == NULL)
691     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
692
693   return ptr;
694 }
695
696 void *checked_calloc(unsigned long size)
697 {
698   void *ptr;
699
700   ptr = calloc(1, size);
701
702   if (ptr == NULL)
703     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
704
705   return ptr;
706 }
707
708 void *checked_realloc(void *ptr, unsigned long size)
709 {
710   ptr = realloc(ptr, size);
711
712   if (ptr == NULL)
713     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
714
715   return ptr;
716 }
717
718 inline void swap_numbers(int *i1, int *i2)
719 {
720   int help = *i1;
721
722   *i1 = *i2;
723   *i2 = help;
724 }
725
726 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
727 {
728   int help_x = *x1;
729   int help_y = *y1;
730
731   *x1 = *x2;
732   *x2 = help_x;
733
734   *y1 = *y2;
735   *y2 = help_y;
736 }
737
738 short getFile16BitInteger(FILE *file, int byte_order)
739 {
740   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
741     return ((fgetc(file) <<  8) |
742             (fgetc(file) <<  0));
743   else           /* BYTE_ORDER_LITTLE_ENDIAN */
744     return ((fgetc(file) <<  0) |
745             (fgetc(file) <<  8));
746 }
747
748 void putFile16BitInteger(FILE *file, short value, int byte_order)
749 {
750   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
751   {
752     fputc((value >>  8) & 0xff, file);
753     fputc((value >>  0) & 0xff, file);
754   }
755   else           /* BYTE_ORDER_LITTLE_ENDIAN */
756   {
757     fputc((value >>  0) & 0xff, file);
758     fputc((value >>  8) & 0xff, file);
759   }
760 }
761
762 int getFile32BitInteger(FILE *file, int byte_order)
763 {
764   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
765     return ((fgetc(file) << 24) |
766             (fgetc(file) << 16) |
767             (fgetc(file) <<  8) |
768             (fgetc(file) <<  0));
769   else           /* BYTE_ORDER_LITTLE_ENDIAN */
770     return ((fgetc(file) <<  0) |
771             (fgetc(file) <<  8) |
772             (fgetc(file) << 16) |
773             (fgetc(file) << 24));
774 }
775
776 void putFile32BitInteger(FILE *file, int value, int byte_order)
777 {
778   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
779   {
780     fputc((value >> 24) & 0xff, file);
781     fputc((value >> 16) & 0xff, file);
782     fputc((value >>  8) & 0xff, file);
783     fputc((value >>  0) & 0xff, file);
784   }
785   else           /* BYTE_ORDER_LITTLE_ENDIAN */
786   {
787     fputc((value >>  0) & 0xff, file);
788     fputc((value >>  8) & 0xff, file);
789     fputc((value >> 16) & 0xff, file);
790     fputc((value >> 24) & 0xff, file);
791   }
792 }
793
794 boolean getFileChunk(FILE *file, char *chunk_name, int *chunk_size,
795                      int byte_order)
796 {
797   const int chunk_name_length = 4;
798
799   /* read chunk name */
800   fgets(chunk_name, chunk_name_length + 1, file);
801
802   if (chunk_size != NULL)
803   {
804     /* read chunk size */
805     *chunk_size = getFile32BitInteger(file, byte_order);
806   }
807
808   return (feof(file) || ferror(file) ? FALSE : TRUE);
809 }
810
811 void putFileChunk(FILE *file, char *chunk_name, int chunk_size,
812                   int byte_order)
813 {
814   /* write chunk name */
815   fputs(chunk_name, file);
816
817   if (chunk_size >= 0)
818   {
819     /* write chunk size */
820     putFile32BitInteger(file, chunk_size, byte_order);
821   }
822 }
823
824 void ReadUnusedBytesFromFile(FILE *file, unsigned long bytes)
825 {
826   while (bytes-- && !feof(file))
827     fgetc(file);
828 }
829
830 void WriteUnusedBytesToFile(FILE *file, unsigned long bytes)
831 {
832   while (bytes--)
833     fputc(0, file);
834 }
835
836 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
837 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
838 #define TRANSLATE_KEYNAME_TO_KEYSYM     2
839 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  3
840
841 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
842 {
843   static struct
844   {
845     Key key;
846     char *x11name;
847     char *name;
848   } translate_key[] =
849   {
850     /* normal cursor keys */
851     { KSYM_Left,        "XK_Left",              "cursor left" },
852     { KSYM_Right,       "XK_Right",             "cursor right" },
853     { KSYM_Up,          "XK_Up",                "cursor up" },
854     { KSYM_Down,        "XK_Down",              "cursor down" },
855
856     /* keypad cursor keys */
857 #ifdef KSYM_KP_Left
858     { KSYM_KP_Left,     "XK_KP_Left",           "keypad left" },
859     { KSYM_KP_Right,    "XK_KP_Right",          "keypad right" },
860     { KSYM_KP_Up,       "XK_KP_Up",             "keypad up" },
861     { KSYM_KP_Down,     "XK_KP_Down",           "keypad down" },
862 #endif
863
864     /* other keypad keys */
865 #ifdef KSYM_KP_Enter
866     { KSYM_KP_Enter,    "XK_KP_Enter",          "keypad enter" },
867     { KSYM_KP_Add,      "XK_KP_Add",            "keypad +" },
868     { KSYM_KP_Subtract, "XK_KP_Subtract",       "keypad -" },
869     { KSYM_KP_Multiply, "XK_KP_Multiply",       "keypad mltply" },
870     { KSYM_KP_Divide,   "XK_KP_Divide",         "keypad /" },
871     { KSYM_KP_Separator,"XK_KP_Separator",      "keypad ," },
872 #endif
873
874     /* modifier keys */
875     { KSYM_Shift_L,     "XK_Shift_L",           "left shift" },
876     { KSYM_Shift_R,     "XK_Shift_R",           "right shift" },
877     { KSYM_Control_L,   "XK_Control_L",         "left control" },
878     { KSYM_Control_R,   "XK_Control_R",         "right control" },
879     { KSYM_Meta_L,      "XK_Meta_L",            "left meta" },
880     { KSYM_Meta_R,      "XK_Meta_R",            "right meta" },
881     { KSYM_Alt_L,       "XK_Alt_L",             "left alt" },
882     { KSYM_Alt_R,       "XK_Alt_R",             "right alt" },
883     { KSYM_Super_L,     "XK_Super_L",           "left super" },  /* Win-L */
884     { KSYM_Super_R,     "XK_Super_R",           "right super" }, /* Win-R */
885     { KSYM_Mode_switch, "XK_Mode_switch",       "mode switch" }, /* Alt-R */
886     { KSYM_Multi_key,   "XK_Multi_key",         "multi key" },   /* Ctrl-R */
887
888     /* some special keys */
889     { KSYM_BackSpace,   "XK_BackSpace",         "backspace" },
890     { KSYM_Delete,      "XK_Delete",            "delete" },
891     { KSYM_Insert,      "XK_Insert",            "insert" },
892     { KSYM_Tab,         "XK_Tab",               "tab" },
893     { KSYM_Home,        "XK_Home",              "home" },
894     { KSYM_End,         "XK_End",               "end" },
895     { KSYM_Page_Up,     "XK_Page_Up",           "page up" },
896     { KSYM_Page_Down,   "XK_Page_Down",         "page down" },
897     { KSYM_Menu,        "XK_Menu",              "menu" },        /* Win-Menu */
898
899     /* ASCII 0x20 to 0x40 keys (except numbers) */
900     { KSYM_space,       "XK_space",             "space" },
901     { KSYM_exclam,      "XK_exclam",            "!" },
902     { KSYM_quotedbl,    "XK_quotedbl",          "\"" },
903     { KSYM_numbersign,  "XK_numbersign",        "#" },
904     { KSYM_dollar,      "XK_dollar",            "$" },
905     { KSYM_percent,     "XK_percent",           "%" },
906     { KSYM_ampersand,   "XK_ampersand",         "&" },
907     { KSYM_apostrophe,  "XK_apostrophe",        "'" },
908     { KSYM_parenleft,   "XK_parenleft",         "(" },
909     { KSYM_parenright,  "XK_parenright",        ")" },
910     { KSYM_asterisk,    "XK_asterisk",          "*" },
911     { KSYM_plus,        "XK_plus",              "+" },
912     { KSYM_comma,       "XK_comma",             "," },
913     { KSYM_minus,       "XK_minus",             "-" },
914     { KSYM_period,      "XK_period",            "." },
915     { KSYM_slash,       "XK_slash",             "/" },
916     { KSYM_colon,       "XK_colon",             ":" },
917     { KSYM_semicolon,   "XK_semicolon",         ";" },
918     { KSYM_less,        "XK_less",              "<" },
919     { KSYM_equal,       "XK_equal",             "=" },
920     { KSYM_greater,     "XK_greater",           ">" },
921     { KSYM_question,    "XK_question",          "?" },
922     { KSYM_at,          "XK_at",                "@" },
923
924     /* more ASCII keys */
925     { KSYM_bracketleft, "XK_bracketleft",       "[" },
926     { KSYM_backslash,   "XK_backslash",         "backslash" },
927     { KSYM_bracketright,"XK_bracketright",      "]" },
928     { KSYM_asciicircum, "XK_asciicircum",       "circumflex" },
929     { KSYM_underscore,  "XK_underscore",        "_" },
930     { KSYM_grave,       "XK_grave",             "grave" },
931     { KSYM_quoteleft,   "XK_quoteleft",         "quote left" },
932     { KSYM_braceleft,   "XK_braceleft",         "brace left" },
933     { KSYM_bar,         "XK_bar",               "bar" },
934     { KSYM_braceright,  "XK_braceright",        "brace right" },
935     { KSYM_asciitilde,  "XK_asciitilde",        "ascii tilde" },
936
937     /* special (non-ASCII) keys */
938     { KSYM_Adiaeresis,  "XK_Adiaeresis",        "Ä" },
939     { KSYM_Odiaeresis,  "XK_Odiaeresis",        "Ö" },
940     { KSYM_Udiaeresis,  "XK_Udiaeresis",        "Ãœ" },
941     { KSYM_adiaeresis,  "XK_adiaeresis",        "ä" },
942     { KSYM_odiaeresis,  "XK_odiaeresis",        "ö" },
943     { KSYM_udiaeresis,  "XK_udiaeresis",        "ü" },
944     { KSYM_ssharp,      "XK_ssharp",            "sharp s" },
945
946     /* end-of-array identifier */
947     { 0,                NULL,                   NULL }
948   };
949
950   int i;
951
952   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
953   {
954     static char name_buffer[30];
955     Key key = *keysym;
956
957     if (key >= KSYM_A && key <= KSYM_Z)
958       sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
959     else if (key >= KSYM_a && key <= KSYM_z)
960       sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
961     else if (key >= KSYM_0 && key <= KSYM_9)
962       sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
963     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
964       sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
965     else if (key >= KSYM_F1 && key <= KSYM_F24)
966       sprintf(name_buffer, "function F%d", (int)(key - KSYM_F1 + 1));
967     else if (key == KSYM_UNDEFINED)
968       strcpy(name_buffer, "(undefined)");
969     else
970     {
971       i = 0;
972
973       do
974       {
975         if (key == translate_key[i].key)
976         {
977           strcpy(name_buffer, translate_key[i].name);
978           break;
979         }
980       }
981       while (translate_key[++i].name);
982
983       if (!translate_key[i].name)
984         strcpy(name_buffer, "(unknown)");
985     }
986
987     *name = name_buffer;
988   }
989   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
990   {
991     static char name_buffer[30];
992     Key key = *keysym;
993
994     if (key >= KSYM_A && key <= KSYM_Z)
995       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
996     else if (key >= KSYM_a && key <= KSYM_z)
997       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
998     else if (key >= KSYM_0 && key <= KSYM_9)
999       sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1000     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1001       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1002     else if (key >= KSYM_F1 && key <= KSYM_F24)
1003       sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_F1 + 1));
1004     else if (key == KSYM_UNDEFINED)
1005       strcpy(name_buffer, "[undefined]");
1006     else
1007     {
1008       i = 0;
1009
1010       do
1011       {
1012         if (key == translate_key[i].key)
1013         {
1014           strcpy(name_buffer, translate_key[i].x11name);
1015           break;
1016         }
1017       }
1018       while (translate_key[++i].x11name);
1019
1020       if (!translate_key[i].x11name)
1021         sprintf(name_buffer, "0x%04lx", (unsigned long)key);
1022     }
1023
1024     *x11name = name_buffer;
1025   }
1026   else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1027   {
1028     Key key = KSYM_UNDEFINED;
1029
1030     i = 0;
1031     do
1032     {
1033       if (strcmp(translate_key[i].name, *name) == 0)
1034       {
1035         key = translate_key[i].key;
1036         break;
1037       }
1038     }
1039     while (translate_key[++i].x11name);
1040
1041     if (key == KSYM_UNDEFINED)
1042       Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1043
1044     *keysym = key;
1045   }
1046   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1047   {
1048     Key key = KSYM_UNDEFINED;
1049     char *name_ptr = *x11name;
1050
1051     if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
1052     {
1053       char c = name_ptr[3];
1054
1055       if (c >= 'A' && c <= 'Z')
1056         key = KSYM_A + (Key)(c - 'A');
1057       else if (c >= 'a' && c <= 'z')
1058         key = KSYM_a + (Key)(c - 'a');
1059       else if (c >= '0' && c <= '9')
1060         key = KSYM_0 + (Key)(c - '0');
1061     }
1062     else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
1063     {
1064       char c = name_ptr[6];
1065
1066       if (c >= '0' && c <= '9')
1067         key = KSYM_0 + (Key)(c - '0');
1068     }
1069     else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
1070     {
1071       char c1 = name_ptr[4];
1072       char c2 = name_ptr[5];
1073       int d = 0;
1074
1075       if ((c1 >= '0' && c1 <= '9') &&
1076           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1077         d = atoi(&name_ptr[4]);
1078
1079       if (d >=1 && d <= 24)
1080         key = KSYM_F1 + (Key)(d - 1);
1081     }
1082     else if (strncmp(name_ptr, "XK_", 3) == 0)
1083     {
1084       i = 0;
1085
1086       do
1087       {
1088         if (strcmp(name_ptr, translate_key[i].x11name) == 0)
1089         {
1090           key = translate_key[i].key;
1091           break;
1092         }
1093       }
1094       while (translate_key[++i].x11name);
1095     }
1096     else if (strncmp(name_ptr, "0x", 2) == 0)
1097     {
1098       unsigned long value = 0;
1099
1100       name_ptr += 2;
1101
1102       while (name_ptr)
1103       {
1104         char c = *name_ptr++;
1105         int d = -1;
1106
1107         if (c >= '0' && c <= '9')
1108           d = (int)(c - '0');
1109         else if (c >= 'a' && c <= 'f')
1110           d = (int)(c - 'a' + 10);
1111         else if (c >= 'A' && c <= 'F')
1112           d = (int)(c - 'A' + 10);
1113
1114         if (d == -1)
1115         {
1116           value = -1;
1117           break;
1118         }
1119
1120         value = value * 16 + d;
1121       }
1122
1123       if (value != -1)
1124         key = (Key)value;
1125     }
1126
1127     *keysym = key;
1128   }
1129 }
1130
1131 char *getKeyNameFromKey(Key key)
1132 {
1133   char *name;
1134
1135   translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1136   return name;
1137 }
1138
1139 char *getX11KeyNameFromKey(Key key)
1140 {
1141   char *x11name;
1142
1143   translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1144   return x11name;
1145 }
1146
1147 Key getKeyFromKeyName(char *name)
1148 {
1149   Key key;
1150
1151   translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1152   return key;
1153 }
1154
1155 Key getKeyFromX11KeyName(char *x11name)
1156 {
1157   Key key;
1158
1159   translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1160   return key;
1161 }
1162
1163 char getCharFromKey(Key key)
1164 {
1165   char *keyname = getKeyNameFromKey(key);
1166   char letter = 0;
1167
1168   if (strlen(keyname) == 1)
1169     letter = keyname[0];
1170   else if (strcmp(keyname, "space") == 0)
1171     letter = ' ';
1172   else if (strcmp(keyname, "circumflex") == 0)
1173     letter = '^';
1174
1175   return letter;
1176 }
1177
1178
1179 /* ========================================================================= */
1180 /* functions for checking filenames                                          */
1181 /* ========================================================================= */
1182
1183 boolean FileIsGraphic(char *filename)
1184 {
1185   if (strlen(filename) > 4 &&
1186       strcmp(&filename[strlen(filename) - 4], ".pcx") == 0)
1187     return TRUE;
1188
1189   return FALSE;
1190 }
1191
1192 boolean FileIsSound(char *basename)
1193 {
1194   if (strlen(basename) > 4 &&
1195       strcmp(&basename[strlen(basename) - 4], ".wav") == 0)
1196     return TRUE;
1197
1198   return FALSE;
1199 }
1200
1201 boolean FileIsMusic(char *basename)
1202 {
1203   /* "music" can be a WAV (loop) file or (if compiled with SDL) a MOD file */
1204
1205   if (FileIsSound(basename))
1206     return TRUE;
1207
1208 #if defined(TARGET_SDL)
1209   if (strlen(basename) > 4 &&
1210       (strcmp(&basename[strlen(basename) - 4], ".mod") == 0 ||
1211        strcmp(&basename[strlen(basename) - 4], ".MOD") == 0 ||
1212        strncmp(basename, "mod.", 4) == 0 ||
1213        strncmp(basename, "MOD.", 4) == 0))
1214     return TRUE;
1215 #endif
1216
1217   return FALSE;
1218 }
1219
1220 boolean FileIsArtworkType(char *basename, int type)
1221 {
1222   if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(basename)) ||
1223       (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(basename)) ||
1224       (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(basename)))
1225     return TRUE;
1226
1227   return FALSE;
1228 }
1229
1230
1231 /* ========================================================================= */
1232 /* functions only needed for non-Unix (non-command-line) systems */
1233 /* ========================================================================= */
1234
1235 #if !defined(PLATFORM_UNIX)
1236
1237 #define ERROR_FILENAME          "error.out"
1238
1239 void initErrorFile()
1240 {
1241   char *filename;
1242
1243   InitUserDataDirectory();
1244
1245   filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1246   unlink(filename);
1247   free(filename);
1248 }
1249
1250 FILE *openErrorFile()
1251 {
1252   char *filename;
1253   FILE *error_file;
1254
1255   filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1256   error_file = fopen(filename, MODE_APPEND);
1257   free(filename);
1258
1259   return error_file;
1260 }
1261
1262 void dumpErrorFile()
1263 {
1264   char *filename;
1265   FILE *error_file;
1266
1267   filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1268   error_file = fopen(filename, MODE_READ);
1269   free(filename);
1270
1271   if (error_file != NULL)
1272   {
1273     while (!feof(error_file))
1274       fputc(fgetc(error_file), stderr);
1275
1276     fclose(error_file);
1277   }
1278 }
1279 #endif
1280
1281
1282 /* ========================================================================= */
1283 /* the following is only for debugging purpose and normally not used         */
1284 /* ========================================================================= */
1285
1286 #define DEBUG_NUM_TIMESTAMPS    3
1287
1288 void debug_print_timestamp(int counter_nr, char *message)
1289 {
1290   static long counter[DEBUG_NUM_TIMESTAMPS][2];
1291
1292   if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
1293     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
1294
1295   counter[counter_nr][0] = Counter();
1296
1297   if (message)
1298     printf("%s %.2f seconds\n", message,
1299            (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
1300
1301   counter[counter_nr][1] = Counter();
1302 }