rnd-20000917-1-src
[rocksndiamonds.git] / src / misc.c
1 /***********************************************************
2 *  Rocks'n'Diamonds -- McDuffin Strikes Back!              *
3 *----------------------------------------------------------*
4 *  (c) 1995-98 Artsoft Entertainment                       *
5 *              Holger Schemel                              *
6 *              Oststrasse 11a                              *
7 *              33604 Bielefeld                             *
8 *              phone: ++49 +521 290471                     *
9 *              email: aeglos@valinor.owl.de                *
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
20 #ifndef WIN32
21 #include <pwd.h>
22 #include <sys/param.h>
23 #endif
24
25 #include "misc.h"
26 #include "init.h"
27 #include "tools.h"
28 #include "sound.h"
29 #include "random.h"
30 #include "joystick.h"
31 #include "files.h"
32
33 #ifdef MSDOS
34 volatile unsigned long counter = 0;
35
36 void increment_counter()
37 {
38   counter++;
39 }
40
41 END_OF_FUNCTION(increment_counter);
42 #endif
43
44
45 /* maximal allowed length of a command line option */
46 #define MAX_OPTION_LEN          256
47
48 #ifdef USE_SDL_LIBRARY
49
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 /* !USE_SDL_LIBRARY */
68 #ifndef MSDOS
69
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
88 #endif /* !MSDOS */
89 #endif /* !USE_SDL_LIBRARY */
90
91 void InitCounter()              /* set counter back to zero */
92 {
93 #ifndef MSDOS
94   mainCounter(INIT_COUNTER);
95 #else
96   LOCK_VARIABLE(counter);
97   LOCK_FUNCTION(increment_counter);
98   install_int_ex(increment_counter, BPS_TO_TIMER(100));
99 #endif
100 }
101
102 unsigned long Counter() /* get milliseconds since last call of InitCounter() */
103 {
104 #ifndef MSDOS
105   return mainCounter(READ_COUNTER);
106 #else
107   return (counter * 10);
108 #endif
109 }
110
111 static void sleep_milliseconds(unsigned long milliseconds_delay)
112 {
113   boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
114
115 #ifdef MSDOS
116   /* don't use select() to perform waiting operations under DOS/Windows
117      environment; always use a busy loop for waiting instead */
118   do_busy_waiting = TRUE;
119 #endif
120
121   if (do_busy_waiting)
122   {
123     /* we want to wait only a few ms -- if we assume that we have a
124        kernel timer resolution of 10 ms, we would wait far to long;
125        therefore it's better to do a short interval of busy waiting
126        to get our sleeping time more accurate */
127
128     unsigned long base_counter = Counter(), actual_counter = Counter();
129
130     while (actual_counter < base_counter + milliseconds_delay &&
131            actual_counter >= base_counter)
132       actual_counter = Counter();
133   }
134   else
135   {
136 #ifdef USE_SDL_LIBRARY
137     SDL_Delay(milliseconds_delay);
138 #else /* !USE_SDL_LIBRARY */
139     struct timeval delay;
140
141     delay.tv_sec  = milliseconds_delay / 1000;
142     delay.tv_usec = 1000 * (milliseconds_delay % 1000);
143
144     if (select(0, NULL, NULL, NULL, &delay) != 0)
145       Error(ERR_WARN, "sleep_milliseconds(): select() failed");
146 #endif /* !USE_SDL_LIBRARY */
147   }
148 }
149
150 void Delay(unsigned long delay) /* Sleep specified number of milliseconds */
151 {
152   sleep_milliseconds(delay);
153 }
154
155 boolean FrameReached(unsigned long *frame_counter_var,
156                      unsigned long frame_delay)
157 {
158   unsigned long actual_frame_counter = FrameCounter;
159
160   if (actual_frame_counter < *frame_counter_var+frame_delay &&
161       actual_frame_counter >= *frame_counter_var)
162     return(FALSE);
163
164   *frame_counter_var = actual_frame_counter;
165   return(TRUE);
166 }
167
168 boolean DelayReached(unsigned long *counter_var,
169                      unsigned long delay)
170 {
171   unsigned long actual_counter = Counter();
172
173   if (actual_counter < *counter_var + delay &&
174       actual_counter >= *counter_var)
175     return(FALSE);
176
177   *counter_var = actual_counter;
178   return(TRUE);
179 }
180
181 void WaitUntilDelayReached(unsigned long *counter_var, unsigned long delay)
182 {
183   unsigned long actual_counter;
184
185   while(1)
186   {
187     actual_counter = Counter();
188
189     if (actual_counter < *counter_var + delay &&
190         actual_counter >= *counter_var)
191       sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
192     else
193       break;
194   }
195
196   *counter_var = actual_counter;
197 }
198
199 /* int2str() returns a number converted to a string;
200    the used memory is static, but will be overwritten by later calls,
201    so if you want to save the result, copy it to a private string buffer;
202    there can be 10 local calls of int2str() without buffering the result --
203    the 11th call will then destroy the result from the first call and so on.
204 */
205
206 char *int2str(int number, int size)
207 {
208   static char shift_array[10][40];
209   static int shift_counter = 0;
210   char *s = shift_array[shift_counter];
211
212   shift_counter = (shift_counter + 1) % 10;
213
214   if (size > 20)
215     size = 20;
216
217   if (size)
218   {
219     sprintf(s, "                    %09d", number);
220     return &s[strlen(s) - size];
221   }
222   else
223   {
224     sprintf(s, "%d", number);
225     return s;
226   }
227 }
228
229 unsigned int SimpleRND(unsigned int max)
230 {
231 #ifdef USE_SDL_LIBRARY
232
233   static unsigned long root = 654321;
234   unsigned long current_ms;
235
236   current_ms = SDL_GetTicks();
237   root = root * 4253261 + current_ms;
238   return (root % max);
239
240 #else /* !USE_SDL_LIBRARY */
241
242   static unsigned long root = 654321;
243   struct timeval current_time;
244
245   gettimeofday(&current_time, NULL);
246   root = root * 4253261 + current_time.tv_sec + current_time.tv_usec;
247   return (root % max);
248
249 #endif /* !USE_SDL_LIBRARY */
250 }
251
252 #ifdef DEBUG
253 static unsigned int last_RND_value = 0;
254
255 unsigned int last_RND()
256 {
257   return last_RND_value;
258 }
259 #endif
260
261 unsigned int RND(unsigned int max)
262 {
263 #ifdef DEBUG
264   return (last_RND_value = random_linux_libc() % max);
265 #else
266   return (random_linux_libc() % max);
267 #endif
268 }
269
270 unsigned int InitRND(long seed)
271 {
272 #ifdef USE_SDL_LIBRARY
273   unsigned long current_ms;
274
275   if (seed == NEW_RANDOMIZE)
276   {
277     current_ms = SDL_GetTicks();
278     srandom_linux_libc((unsigned int) current_ms);
279     return (unsigned int) current_ms;
280   }
281   else
282   {
283     srandom_linux_libc((unsigned int) seed);
284     return (unsigned int) seed;
285   }
286 #else /* !USE_SDL_LIBRARY */
287   struct timeval current_time;
288
289   if (seed == NEW_RANDOMIZE)
290   {
291     gettimeofday(&current_time, NULL);
292     srandom_linux_libc((unsigned int) current_time.tv_usec);
293     return (unsigned int) current_time.tv_usec;
294   }
295   else
296   {
297     srandom_linux_libc((unsigned int) seed);
298     return (unsigned int) seed;
299   }
300 #endif /* !USE_SDL_LIBRARY */
301 }
302
303 char *getLoginName()
304 {
305 #ifdef WIN32
306   return ANONYMOUS_NAME;
307 #else
308   struct passwd *pwd;
309
310   if ((pwd = getpwuid(getuid())) == NULL)
311     return ANONYMOUS_NAME;
312   else
313     return pwd->pw_name;
314 #endif
315 }
316
317 char *getRealName()
318 {
319 #if defined(MSDOS) || defined(WIN32)
320   return ANONYMOUS_NAME;
321 #else
322   struct passwd *pwd;
323
324   if ((pwd = getpwuid(getuid())) == NULL || strlen(pwd->pw_gecos) == 0)
325     return ANONYMOUS_NAME;
326   else
327   {
328     static char real_name[1024];
329     char *from_ptr = pwd->pw_gecos, *to_ptr = real_name;
330
331     if (strchr(pwd->pw_gecos, 'ß') == NULL)
332       return pwd->pw_gecos;
333
334     /* the user's real name contains a 'ß' character (german sharp s),
335        which has no equivalent in upper case letters (which our fonts use) */
336     while (*from_ptr != '\0' && (long)(to_ptr - real_name) < 1024 - 2)
337     {
338       if (*from_ptr != 'ß')
339         *to_ptr++ = *from_ptr++;
340       else
341       {
342         from_ptr++;
343         *to_ptr++ = 's';
344         *to_ptr++ = 's';
345       }
346     }
347     *to_ptr = '\0';
348
349     return real_name;
350   }
351 #endif
352 }
353
354 char *getHomeDir()
355 {
356 #if defined(MSDOS) || defined(WIN32)
357   return ".";
358 #else
359   static char *home_dir = NULL;
360
361   if (!home_dir)
362   {
363     if (!(home_dir = getenv("HOME")))
364     {
365       struct passwd *pwd;
366
367       if ((pwd = getpwuid(getuid())))
368         home_dir = pwd->pw_dir;
369       else
370         home_dir = ".";
371     }
372   }
373
374   return home_dir;
375 #endif
376 }
377
378 char *getPath2(char *path1, char *path2)
379 {
380   char *complete_path = checked_malloc(strlen(path1) + 1 +
381                                        strlen(path2) + 1);
382
383   sprintf(complete_path, "%s/%s", path1, path2);
384   return complete_path;
385 }
386
387 char *getPath3(char *path1, char *path2, char *path3)
388 {
389   char *complete_path = checked_malloc(strlen(path1) + 1 +
390                                        strlen(path2) + 1 +
391                                        strlen(path3) + 1);
392
393   sprintf(complete_path, "%s/%s/%s", path1, path2, path3);
394   return complete_path;
395 }
396
397 char *getStringCopy(char *s)
398 {
399   char *s_copy;
400
401   if (s == NULL)
402     return NULL;
403
404   s_copy = checked_malloc(strlen(s) + 1);
405
406   strcpy(s_copy, s);
407   return s_copy;
408 }
409
410 char *getStringToLower(char *s)
411 {
412   char *s_copy = checked_malloc(strlen(s) + 1);
413   char *s_ptr = s_copy;
414
415   while (*s)
416     *s_ptr++ = tolower(*s++);
417   *s_ptr = '\0';
418
419   return s_copy;
420 }
421
422 void MarkTileDirty(int x, int y)
423 {
424   int xx = redraw_x1 + x;
425   int yy = redraw_y1 + y;
426
427   if (!redraw[xx][yy])
428     redraw_tiles++;
429
430   redraw[xx][yy] = TRUE;
431   redraw_mask |= REDRAW_TILES;
432 }
433
434 void SetBorderElement()
435 {
436   int x, y;
437
438   BorderElement = EL_LEERRAUM;
439
440   for(y=0; y<lev_fieldy && BorderElement == EL_LEERRAUM; y++)
441   {
442     for(x=0; x<lev_fieldx; x++)
443     {
444       if (!IS_MASSIVE(Feld[x][y]))
445         BorderElement = EL_BETON;
446
447       if (y != 0 && y != lev_fieldy - 1 && x != lev_fieldx - 1)
448         x = lev_fieldx - 2;
449     }
450   }
451 }
452
453 void GetOptions(char *argv[])
454 {
455   char **options_left = &argv[1];
456
457   /* initialize global program options */
458   options.display_name = NULL;
459   options.server_host = NULL;
460   options.server_port = 0;
461   options.ro_base_directory = RO_BASE_PATH;
462   options.rw_base_directory = RW_BASE_PATH;
463   options.level_directory = RO_BASE_PATH "/" LEVELS_DIRECTORY;
464   options.serveronly = FALSE;
465   options.network = FALSE;
466   options.verbose = FALSE;
467   options.debug = FALSE;
468
469   /* initialize some more global variables */
470   global.frames_per_second = 0;
471   global.fps_slowdown = FALSE;
472   global.fps_slowdown_factor = 1;
473
474   while (*options_left)
475   {
476     char option_str[MAX_OPTION_LEN];
477     char *option = options_left[0];
478     char *next_option = options_left[1];
479     char *option_arg = NULL;
480     int option_len = strlen(option);
481
482     if (option_len >= MAX_OPTION_LEN)
483       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
484
485     strcpy(option_str, option);                 /* copy argument into buffer */
486     option = option_str;
487
488     if (strcmp(option, "--") == 0)              /* stop scanning arguments */
489       break;
490
491     if (strncmp(option, "--", 2) == 0)          /* treat '--' like '-' */
492       option++;
493
494     option_arg = strchr(option, '=');
495     if (option_arg == NULL)                     /* no '=' in option */
496       option_arg = next_option;
497     else
498     {
499       *option_arg++ = '\0';                     /* cut argument from option */
500       if (*option_arg == '\0')                  /* no argument after '=' */
501         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
502     }
503
504     option_len = strlen(option);
505
506     if (strcmp(option, "-") == 0)
507       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
508     else if (strncmp(option, "-help", option_len) == 0)
509     {
510       printf("Usage: %s [options] [server.name [port]]\n"
511              "Options:\n"
512              "  -d, --display machine:0       X server display\n"
513              "  -b, --basepath directory      alternative base directory\n"
514              "  -l, --level directory         alternative level directory\n"
515              "  -s, --serveronly              only start network server\n"
516              "  -n, --network                 network multiplayer game\n"
517              "  -v, --verbose                 verbose mode\n",
518              program_name);
519       exit(0);
520     }
521     else if (strncmp(option, "-display", option_len) == 0)
522     {
523       if (option_arg == NULL)
524         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
525
526       options.display_name = option_arg;
527       if (option_arg == next_option)
528         options_left++;
529     }
530     else if (strncmp(option, "-basepath", option_len) == 0)
531     {
532       if (option_arg == NULL)
533         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
534
535       /* this should be extended to separate options for ro and rw data */
536       options.ro_base_directory = option_arg;
537       options.rw_base_directory = option_arg;
538       if (option_arg == next_option)
539         options_left++;
540
541       /* adjust path for level directory accordingly */
542       options.level_directory =
543         getPath2(options.ro_base_directory, LEVELS_DIRECTORY);
544     }
545     else if (strncmp(option, "-levels", option_len) == 0)
546     {
547       if (option_arg == NULL)
548         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
549
550       options.level_directory = option_arg;
551       if (option_arg == next_option)
552         options_left++;
553     }
554     else if (strncmp(option, "-network", option_len) == 0)
555     {
556       options.network = TRUE;
557     }
558     else if (strncmp(option, "-serveronly", option_len) == 0)
559     {
560       options.serveronly = TRUE;
561     }
562     else if (strncmp(option, "-verbose", option_len) == 0)
563     {
564       options.verbose = TRUE;
565     }
566     else if (strncmp(option, "-debug", option_len) == 0)
567     {
568       options.debug = TRUE;
569     }
570     else if (*option == '-')
571     {
572       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
573     }
574     else if (options.server_host == NULL)
575     {
576       options.server_host = *options_left;
577     }
578     else if (options.server_port == 0)
579     {
580       options.server_port = atoi(*options_left);
581       if (options.server_port < 1024)
582         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
583     }
584     else
585       Error(ERR_EXIT_HELP, "too many arguments");
586
587     options_left++;
588   }
589 }
590
591 void Error(int mode, char *format, ...)
592 {
593   char *process_name = "";
594   FILE *error = stderr;
595
596   /* display warnings only when running in verbose mode */
597   if (mode & ERR_WARN && !options.verbose)
598     return;
599
600 #if defined(MSDOS) || defined(WIN32)
601   if ((error = openErrorFile()) == NULL)
602   {
603     printf("Cannot write to error output file!\n");
604     CloseAllAndExit(1);
605   }
606 #endif
607
608   if (mode & ERR_SOUND_SERVER)
609     process_name = " sound server";
610   else if (mode & ERR_NETWORK_SERVER)
611     process_name = " network server";
612   else if (mode & ERR_NETWORK_CLIENT)
613     process_name = " network client **";
614
615   if (format)
616   {
617     va_list ap;
618
619     fprintf(error, "%s%s: ", program_name, process_name);
620
621     if (mode & ERR_WARN)
622       fprintf(error, "warning: ");
623
624     va_start(ap, format);
625     vfprintf(error, format, ap);
626     va_end(ap);
627   
628     fprintf(error, "\n");
629   }
630   
631   if (mode & ERR_HELP)
632     fprintf(error, "%s: Try option '--help' for more information.\n",
633             program_name);
634
635   if (mode & ERR_EXIT)
636     fprintf(error, "%s%s: aborting\n", program_name, process_name);
637
638   if (error != stderr)
639     fclose(error);
640
641   if (mode & ERR_EXIT)
642   {
643     if (mode & ERR_FROM_SERVER)
644       exit(1);                          /* child process: normal exit */
645     else
646       CloseAllAndExit(1);               /* main process: clean up stuff */
647   }
648 }
649
650 void *checked_malloc(unsigned long size)
651 {
652   void *ptr;
653
654   ptr = malloc(size);
655
656   if (ptr == NULL)
657     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
658
659   return ptr;
660 }
661
662 void *checked_calloc(unsigned long size)
663 {
664   void *ptr;
665
666   ptr = calloc(1, size);
667
668   if (ptr == NULL)
669     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
670
671   return ptr;
672 }
673
674 short getFile16BitInteger(FILE *file, int byte_order)
675 {
676   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
677     return ((fgetc(file) <<  8) |
678             (fgetc(file) <<  0));
679   else           /* BYTE_ORDER_LITTLE_ENDIAN */
680     return ((fgetc(file) <<  0) |
681             (fgetc(file) <<  8));
682 }
683
684 void putFile16BitInteger(FILE *file, short value, int byte_order)
685 {
686   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
687   {
688     fputc((value >>  8) & 0xff, file);
689     fputc((value >>  0) & 0xff, file);
690   }
691   else           /* BYTE_ORDER_LITTLE_ENDIAN */
692   {
693     fputc((value >>  0) & 0xff, file);
694     fputc((value >>  8) & 0xff, file);
695   }
696 }
697
698 int getFile32BitInteger(FILE *file, int byte_order)
699 {
700   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
701     return ((fgetc(file) << 24) |
702             (fgetc(file) << 16) |
703             (fgetc(file) <<  8) |
704             (fgetc(file) <<  0));
705   else           /* BYTE_ORDER_LITTLE_ENDIAN */
706     return ((fgetc(file) <<  0) |
707             (fgetc(file) <<  8) |
708             (fgetc(file) << 16) |
709             (fgetc(file) << 24));
710 }
711
712 void putFile32BitInteger(FILE *file, int value, int byte_order)
713 {
714   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
715   {
716     fputc((value >> 24) & 0xff, file);
717     fputc((value >> 16) & 0xff, file);
718     fputc((value >>  8) & 0xff, file);
719     fputc((value >>  0) & 0xff, file);
720   }
721   else           /* BYTE_ORDER_LITTLE_ENDIAN */
722   {
723     fputc((value >>  0) & 0xff, file);
724     fputc((value >>  8) & 0xff, file);
725     fputc((value >> 16) & 0xff, file);
726     fputc((value >> 24) & 0xff, file);
727   }
728 }
729
730 void getFileChunk(FILE *file, char *chunk_buffer, int *chunk_length,
731                   int byte_order)
732 {
733   const int chunk_identifier_length = 4;
734
735   /* read chunk identifier */
736   fgets(chunk_buffer, chunk_identifier_length + 1, file);
737
738   /* read chunk length */
739   *chunk_length = getFile32BitInteger(file, byte_order);
740 }
741
742 void putFileChunk(FILE *file, char *chunk_name, int chunk_length,
743                   int byte_order)
744 {
745   /* write chunk identifier */
746   fputs(chunk_name, file);
747
748   /* write chunk length */
749   putFile32BitInteger(file, chunk_length, byte_order);
750 }
751
752 #define TRANSLATE_KEY_TO_KEYNAME        0
753 #define TRANSLATE_KEY_TO_X11KEYNAME     1
754 #define TRANSLATE_X11KEYNAME_TO_KEY     2
755
756 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
757 {
758   static struct
759   {
760     Key key;
761     char *x11name;
762     char *name;
763   } translate_key[] =
764   {
765     /* normal cursor keys */
766     { KEY_Left,         "XK_Left",              "cursor left" },
767     { KEY_Right,        "XK_Right",             "cursor right" },
768     { KEY_Up,           "XK_Up",                "cursor up" },
769     { KEY_Down,         "XK_Down",              "cursor down" },
770
771     /* keypad cursor keys */
772 #ifdef KEY_KP_Left
773     { KEY_KP_Left,      "XK_KP_Left",           "keypad left" },
774     { KEY_KP_Right,     "XK_KP_Right",          "keypad right" },
775     { KEY_KP_Up,        "XK_KP_Up",             "keypad up" },
776     { KEY_KP_Down,      "XK_KP_Down",           "keypad down" },
777 #endif
778
779     /* other keypad keys */
780 #ifdef KEY_KP_Enter
781     { KEY_KP_Enter,     "XK_KP_Enter",          "keypad enter" },
782     { KEY_KP_Add,       "XK_KP_Add",            "keypad +" },
783     { KEY_KP_Subtract,  "XK_KP_Subtract",       "keypad -" },
784     { KEY_KP_Multiply,  "XK_KP_Multiply",       "keypad mltply" },
785     { KEY_KP_Divide,    "XK_KP_Divide",         "keypad /" },
786     { KEY_KP_Separator, "XK_KP_Separator",      "keypad ," },
787 #endif
788
789     /* modifier keys */
790     { KEY_Shift_L,      "XK_Shift_L",           "left shift" },
791     { KEY_Shift_R,      "XK_Shift_R",           "right shift" },
792     { KEY_Control_L,    "XK_Control_L",         "left control" },
793     { KEY_Control_R,    "XK_Control_R",         "right control" },
794     { KEY_Meta_L,       "XK_Meta_L",            "left meta" },
795     { KEY_Meta_R,       "XK_Meta_R",            "right meta" },
796     { KEY_Alt_L,        "XK_Alt_L",             "left alt" },
797     { KEY_Alt_R,        "XK_Alt_R",             "right alt" },
798     { KEY_Super_L,      "XK_Super_L",           "left super" },  /* Win-L */
799     { KEY_Super_R,      "XK_Super_R",           "right super" }, /* Win-R */
800     { KEY_Mode_switch,  "XK_Mode_switch",       "mode switch" }, /* Alt-R */
801     { KEY_Multi_key,    "XK_Multi_key",         "multi key" },   /* Ctrl-R */
802
803     /* some special keys */
804     { KEY_BackSpace,    "XK_BackSpace",         "backspace" },
805     { KEY_Delete,       "XK_Delete",            "delete" },
806     { KEY_Insert,       "XK_Insert",            "insert" },
807     { KEY_Tab,          "XK_Tab",               "tab" },
808     { KEY_Home,         "XK_Home",              "home" },
809     { KEY_End,          "XK_End",               "end" },
810     { KEY_Page_Up,      "XK_Page_Up",           "page up" },
811     { KEY_Page_Down,    "XK_Page_Down",         "page down" },
812     { KEY_Menu,         "XK_Menu",              "menu" },        /* Win-Menu */
813
814     /* ASCII 0x20 to 0x40 keys (except numbers) */
815     { KEY_space,        "XK_space",             "space" },
816     { KEY_exclam,       "XK_exclam",            "!" },
817     { KEY_quotedbl,     "XK_quotedbl",          "\"" },
818     { KEY_numbersign,   "XK_numbersign",        "#" },
819     { KEY_dollar,       "XK_dollar",            "$" },
820     { KEY_percent,      "XK_percent",           "%" },
821     { KEY_ampersand,    "XK_ampersand",         "&" },
822     { KEY_apostrophe,   "XK_apostrophe",        "'" },
823     { KEY_parenleft,    "XK_parenleft",         "(" },
824     { KEY_parenright,   "XK_parenright",        ")" },
825     { KEY_asterisk,     "XK_asterisk",          "*" },
826     { KEY_plus,         "XK_plus",              "+" },
827     { KEY_comma,        "XK_comma",             "," },
828     { KEY_minus,        "XK_minus",             "-" },
829     { KEY_period,       "XK_period",            "." },
830     { KEY_slash,        "XK_slash",             "/" },
831     { KEY_colon,        "XK_colon",             ":" },
832     { KEY_semicolon,    "XK_semicolon",         ";" },
833     { KEY_less,         "XK_less",              "<" },
834     { KEY_equal,        "XK_equal",             "=" },
835     { KEY_greater,      "XK_greater",           ">" },
836     { KEY_question,     "XK_question",          "?" },
837     { KEY_at,           "XK_at",                "@" },
838
839     /* more ASCII keys */
840     { KEY_bracketleft,  "XK_bracketleft",       "[" },
841     { KEY_backslash,    "XK_backslash",         "backslash" },
842     { KEY_bracketright, "XK_bracketright",      "]" },
843     { KEY_asciicircum,  "XK_asciicircum",       "circumflex" },
844     { KEY_underscore,   "XK_underscore",        "_" },
845     { KEY_grave,        "XK_grave",             "grave" },
846     { KEY_quoteleft,    "XK_quoteleft",         "quote left" },
847     { KEY_braceleft,    "XK_braceleft",         "brace left" },
848     { KEY_bar,          "XK_bar",               "bar" },
849     { KEY_braceright,   "XK_braceright",        "brace right" },
850     { KEY_asciitilde,   "XK_asciitilde",        "ascii tilde" },
851
852     /* special (non-ASCII) keys */
853     { KEY_Adiaeresis,   "XK_Adiaeresis",        "Ä" },
854     { KEY_Odiaeresis,   "XK_Odiaeresis",        "Ö" },
855     { KEY_Udiaeresis,   "XK_Udiaeresis",        "Ãœ" },
856     { KEY_adiaeresis,   "XK_adiaeresis",        "ä" },
857     { KEY_odiaeresis,   "XK_odiaeresis",        "ö" },
858     { KEY_udiaeresis,   "XK_udiaeresis",        "ü" },
859     { KEY_ssharp,       "XK_ssharp",            "sharp s" },
860
861     /* end-of-array identifier */
862     { 0,                NULL,                   NULL }
863   };
864
865   int i;
866
867   if (mode == TRANSLATE_KEY_TO_KEYNAME)
868   {
869     static char name_buffer[30];
870     Key key = *keysym;
871
872     if (key >= KEY_A && key <= KEY_Z)
873       sprintf(name_buffer, "%c", 'A' + (char)(key - KEY_A));
874     else if (key >= KEY_a && key <= KEY_z)
875       sprintf(name_buffer, "%c", 'a' + (char)(key - KEY_a));
876     else if (key >= KEY_0 && key <= KEY_9)
877       sprintf(name_buffer, "%c", '0' + (char)(key - KEY_0));
878     else if (key >= KEY_KP_0 && key <= KEY_KP_9)
879       sprintf(name_buffer, "keypad %c", '0' + (char)(key - KEY_KP_0));
880     else if (key >= KEY_F1 && key <= KEY_F24)
881       sprintf(name_buffer, "function F%d", (int)(key - KEY_F1 + 1));
882     else if (key == KEY_UNDEFINED)
883       strcpy(name_buffer, "(undefined)");
884     else
885     {
886       i = 0;
887
888       do
889       {
890         if (key == translate_key[i].key)
891         {
892           strcpy(name_buffer, translate_key[i].name);
893           break;
894         }
895       }
896       while (translate_key[++i].name);
897
898       if (!translate_key[i].name)
899         strcpy(name_buffer, "(unknown)");
900     }
901
902     *name = name_buffer;
903   }
904   else if (mode == TRANSLATE_KEY_TO_X11KEYNAME)
905   {
906     static char name_buffer[30];
907     Key key = *keysym;
908
909     if (key >= KEY_A && key <= KEY_Z)
910       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KEY_A));
911     else if (key >= KEY_a && key <= KEY_z)
912       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KEY_a));
913     else if (key >= KEY_0 && key <= KEY_9)
914       sprintf(name_buffer, "XK_%c", '0' + (char)(key - KEY_0));
915     else if (key >= KEY_KP_0 && key <= KEY_KP_9)
916       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KEY_KP_0));
917     else if (key >= KEY_F1 && key <= KEY_F24)
918       sprintf(name_buffer, "XK_F%d", (int)(key - KEY_F1 + 1));
919     else if (key == KEY_UNDEFINED)
920       strcpy(name_buffer, "[undefined]");
921     else
922     {
923       i = 0;
924
925       do
926       {
927         if (key == translate_key[i].key)
928         {
929           strcpy(name_buffer, translate_key[i].x11name);
930           break;
931         }
932       }
933       while (translate_key[++i].x11name);
934
935       if (!translate_key[i].x11name)
936         sprintf(name_buffer, "0x%04lx", (unsigned long)key);
937     }
938
939     *x11name = name_buffer;
940   }
941   else if (mode == TRANSLATE_X11KEYNAME_TO_KEY)
942   {
943     Key key = KEY_UNDEFINED;
944     char *name_ptr = *x11name;
945
946     if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
947     {
948       char c = name_ptr[3];
949
950       if (c >= 'A' && c <= 'Z')
951         key = KEY_A + (Key)(c - 'A');
952       else if (c >= 'a' && c <= 'z')
953         key = KEY_a + (Key)(c - 'a');
954       else if (c >= '0' && c <= '9')
955         key = KEY_0 + (Key)(c - '0');
956     }
957     else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
958     {
959       char c = name_ptr[6];
960
961       if (c >= '0' && c <= '9')
962         key = KEY_0 + (Key)(c - '0');
963     }
964     else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
965     {
966       char c1 = name_ptr[4];
967       char c2 = name_ptr[5];
968       int d = 0;
969
970       if ((c1 >= '0' && c1 <= '9') &&
971           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
972         d = atoi(&name_ptr[4]);
973
974       if (d >=1 && d <= 24)
975         key = KEY_F1 + (Key)(d - 1);
976     }
977     else if (strncmp(name_ptr, "XK_", 3) == 0)
978     {
979       i = 0;
980
981       do
982       {
983         if (strcmp(name_ptr, translate_key[i].x11name) == 0)
984         {
985           key = translate_key[i].key;
986           break;
987         }
988       }
989       while (translate_key[++i].x11name);
990     }
991     else if (strncmp(name_ptr, "0x", 2) == 0)
992     {
993       unsigned long value = 0;
994
995       name_ptr += 2;
996
997       while (name_ptr)
998       {
999         char c = *name_ptr++;
1000         int d = -1;
1001
1002         if (c >= '0' && c <= '9')
1003           d = (int)(c - '0');
1004         else if (c >= 'a' && c <= 'f')
1005           d = (int)(c - 'a' + 10);
1006         else if (c >= 'A' && c <= 'F')
1007           d = (int)(c - 'A' + 10);
1008
1009         if (d == -1)
1010         {
1011           value = -1;
1012           break;
1013         }
1014
1015         value = value * 16 + d;
1016       }
1017
1018       if (value != -1)
1019         key = (Key)value;
1020     }
1021
1022     *keysym = key;
1023   }
1024 }
1025
1026 char *getKeyNameFromKey(Key key)
1027 {
1028   char *name;
1029
1030   translate_keyname(&key, NULL, &name, TRANSLATE_KEY_TO_KEYNAME);
1031   return name;
1032 }
1033
1034 char *getX11KeyNameFromKey(Key key)
1035 {
1036   char *x11name;
1037
1038   translate_keyname(&key, &x11name, NULL, TRANSLATE_KEY_TO_X11KEYNAME);
1039   return x11name;
1040 }
1041
1042 Key getKeyFromX11KeyName(char *x11name)
1043 {
1044   Key key;
1045
1046   translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEY);
1047   return key;
1048 }
1049
1050 char getCharFromKey(Key key)
1051 {
1052   char *keyname = getKeyNameFromKey(key);
1053   char letter = 0;
1054
1055   if (strlen(keyname) == 1)
1056     letter = keyname[0];
1057   else if (strcmp(keyname, "space") == 0)
1058     letter = ' ';
1059   else if (strcmp(keyname, "circumflex") == 0)
1060     letter = '^';
1061
1062   return letter;
1063 }
1064
1065 #define TRANSLATE_JOYSYMBOL_TO_JOYNAME  0
1066 #define TRANSLATE_JOYNAME_TO_JOYSYMBOL  1
1067
1068 void translate_joyname(int *joysymbol, char **name, int mode)
1069 {
1070   static struct
1071   {
1072     int joysymbol;
1073     char *name;
1074   } translate_joy[] =
1075   {
1076     { JOY_LEFT,         "joystick_left" },
1077     { JOY_RIGHT,        "joystick_right" },
1078     { JOY_UP,           "joystick_up" },
1079     { JOY_DOWN,         "joystick_down" },
1080     { JOY_BUTTON_1,     "joystick_button_1" },
1081     { JOY_BUTTON_2,     "joystick_button_2" },
1082   };
1083
1084   int i;
1085
1086   if (mode == TRANSLATE_JOYSYMBOL_TO_JOYNAME)
1087   {
1088     *name = "[undefined]";
1089
1090     for (i=0; i<6; i++)
1091     {
1092       if (*joysymbol == translate_joy[i].joysymbol)
1093       {
1094         *name = translate_joy[i].name;
1095         break;
1096       }
1097     }
1098   }
1099   else if (mode == TRANSLATE_JOYNAME_TO_JOYSYMBOL)
1100   {
1101     *joysymbol = 0;
1102
1103     for (i=0; i<6; i++)
1104     {
1105       if (strcmp(*name, translate_joy[i].name) == 0)
1106       {
1107         *joysymbol = translate_joy[i].joysymbol;
1108         break;
1109       }
1110     }
1111   }
1112 }
1113
1114 char *getJoyNameFromJoySymbol(int joysymbol)
1115 {
1116   char *name;
1117
1118   translate_joyname(&joysymbol, &name, TRANSLATE_JOYSYMBOL_TO_JOYNAME);
1119   return name;
1120 }
1121
1122 int getJoySymbolFromJoyName(char *name)
1123 {
1124   int joysymbol;
1125
1126   translate_joyname(&joysymbol, &name, TRANSLATE_JOYNAME_TO_JOYSYMBOL);
1127   return joysymbol;
1128 }
1129
1130 int getJoystickNrFromDeviceName(char *device_name)
1131 {
1132   char c;
1133   int joystick_nr = 0;
1134
1135   if (device_name == NULL || device_name[0] == '\0')
1136     return 0;
1137
1138   c = device_name[strlen(device_name) - 1];
1139
1140   if (c >= '0' && c <= '9')
1141     joystick_nr = (int)(c - '0');
1142
1143   if (joystick_nr < 0 || joystick_nr >= MAX_PLAYERS)
1144     joystick_nr = 0;
1145
1146   return joystick_nr;
1147 }
1148
1149 /* ------------------------------------------------------------------------- */
1150 /* some functions to handle lists of level directories                       */
1151 /* ------------------------------------------------------------------------- */
1152
1153 struct LevelDirInfo *newLevelDirInfo()
1154 {
1155   return checked_calloc(sizeof(struct LevelDirInfo));
1156 }
1157
1158 void pushLevelDirInfo(struct LevelDirInfo **node_first,
1159                       struct LevelDirInfo *node_new)
1160 {
1161   node_new->next = *node_first;
1162   *node_first = node_new;
1163 }
1164
1165 int numLevelDirInfo(struct LevelDirInfo *node)
1166 {
1167   int num = 0;
1168
1169   while (node)
1170   {
1171     num++;
1172     node = node->next;
1173   }
1174
1175   return num;
1176 }
1177
1178 boolean validLevelSeries(struct LevelDirInfo *node)
1179 {
1180   return (node != NULL && !node->node_group && !node->parent_link);
1181 }
1182
1183 struct LevelDirInfo *getFirstValidLevelSeries(struct LevelDirInfo *node)
1184 {
1185   if (node == NULL)
1186   {
1187     if (leveldir_first)         /* start with first level directory entry */
1188       return getFirstValidLevelSeries(leveldir_first);
1189     else
1190       return NULL;
1191   }
1192   else if (node->node_group)    /* enter level group (step down into tree) */
1193     return getFirstValidLevelSeries(node->node_group);
1194   else if (node->parent_link)   /* skip start entry of level group */
1195   {
1196     if (node->next)             /* get first real level series entry */
1197       return getFirstValidLevelSeries(node->next);
1198     else                        /* leave empty level group and go on */
1199       return getFirstValidLevelSeries(node->node_parent->next);
1200   }
1201   else                          /* this seems to be a regular level series */
1202     return node;
1203 }
1204
1205 struct LevelDirInfo *getLevelDirInfoFirstGroupEntry(struct LevelDirInfo *node)
1206 {
1207   if (node == NULL)
1208     return NULL;
1209
1210   if (node->node_parent == NULL)                /* top level group */
1211     return leveldir_first;
1212   else                                          /* sub level group */
1213     return node->node_parent->node_group;
1214 }
1215
1216 int numLevelDirInfoInGroup(struct LevelDirInfo *node)
1217 {
1218   return numLevelDirInfo(getLevelDirInfoFirstGroupEntry(node));
1219 }
1220
1221 int posLevelDirInfo(struct LevelDirInfo *node)
1222 {
1223   struct LevelDirInfo *node_cmp = getLevelDirInfoFirstGroupEntry(node);
1224   int pos = 0;
1225
1226   while (node_cmp)
1227   {
1228     if (node_cmp == node)
1229       return pos;
1230
1231     pos++;
1232     node_cmp = node_cmp->next;
1233   }
1234
1235   return 0;
1236 }
1237
1238 struct LevelDirInfo *getLevelDirInfoFromPos(struct LevelDirInfo *node, int pos)
1239 {
1240   struct LevelDirInfo *node_default = node;
1241   int pos_cmp = 0;
1242
1243   while (node)
1244   {
1245     if (pos_cmp == pos)
1246       return node;
1247
1248     pos_cmp++;
1249     node = node->next;
1250   }
1251
1252   return node_default;
1253 }
1254
1255 struct LevelDirInfo *getLevelDirInfoFromFilenameExt(struct LevelDirInfo *node,
1256                                                     char *filename)
1257 {
1258   if (filename == NULL)
1259     return NULL;
1260
1261   while (node)
1262   {
1263     if (node->node_group)
1264     {
1265       struct LevelDirInfo *node_group;
1266
1267       node_group = getLevelDirInfoFromFilenameExt(node->node_group, filename);
1268
1269       if (node_group)
1270         return node_group;
1271     }
1272     else if (!node->parent_link)
1273     {
1274       if (strcmp(filename, node->filename) == 0)
1275         return node;
1276     }
1277
1278     node = node->next;
1279   }
1280
1281   return NULL;
1282 }
1283
1284 struct LevelDirInfo *getLevelDirInfoFromFilename(char *filename)
1285 {
1286   return getLevelDirInfoFromFilenameExt(leveldir_first, filename);
1287 }
1288
1289 void dumpLevelDirInfo(struct LevelDirInfo *node, int depth)
1290 {
1291   int i;
1292
1293   while (node)
1294   {
1295     for (i=0; i<depth * 3; i++)
1296       printf(" ");
1297
1298     printf("filename == '%s'\n", node->filename);
1299
1300     if (node->node_group != NULL)
1301       dumpLevelDirInfo(node->node_group, depth + 1);
1302
1303     node = node->next;
1304   }
1305 }
1306
1307 void sortLevelDirInfo(struct LevelDirInfo **node_first,
1308                       int (*compare_function)(const void *, const void *))
1309 {
1310   int num_nodes = numLevelDirInfo(*node_first);
1311   struct LevelDirInfo **sort_array;
1312   struct LevelDirInfo *node = *node_first;
1313   int i = 0;
1314
1315   if (num_nodes == 0)
1316     return;
1317
1318   /* allocate array for sorting structure pointers */
1319   sort_array = checked_calloc(num_nodes * sizeof(struct LevelDirInfo *));
1320
1321   /* writing structure pointers to sorting array */
1322   while (i < num_nodes && node)         /* double boundary check... */
1323   {
1324     sort_array[i] = node;
1325
1326     i++;
1327     node = node->next;
1328   }
1329
1330   /* sorting the structure pointers in the sorting array */
1331   qsort(sort_array, num_nodes, sizeof(struct LevelDirInfo *),
1332         compare_function);
1333
1334   /* update the linkage of list elements with the sorted node array */
1335   for (i=0; i<num_nodes - 1; i++)
1336     sort_array[i]->next = sort_array[i + 1];
1337   sort_array[num_nodes - 1]->next = NULL;
1338
1339   /* update the linkage of the main list anchor pointer */
1340   *node_first = sort_array[0];
1341
1342   free(sort_array);
1343
1344   /* now recursively sort the level group structures */
1345   node = *node_first;
1346   while (node)
1347   {
1348     if (node->node_group != NULL)
1349       sortLevelDirInfo(&node->node_group, compare_function);
1350
1351     node = node->next;
1352   }
1353 }
1354
1355 inline void swap_numbers(int *i1, int *i2)
1356 {
1357   int help = *i1;
1358
1359   *i1 = *i2;
1360   *i2 = help;
1361 }
1362
1363 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
1364 {
1365   int help_x = *x1;
1366   int help_y = *y1;
1367
1368   *x1 = *x2;
1369   *x2 = help_x;
1370
1371   *y1 = *y2;
1372   *y2 = help_y;
1373 }
1374
1375
1376 /* ------------------------------------------------------------------------- */
1377 /* the following is only for debugging purpose and normally not used         */
1378 /* ------------------------------------------------------------------------- */
1379
1380 #define DEBUG_NUM_TIMESTAMPS    3
1381
1382 void debug_print_timestamp(int counter_nr, char *message)
1383 {
1384   static long counter[DEBUG_NUM_TIMESTAMPS][2];
1385
1386   if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
1387     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
1388
1389   counter[counter_nr][0] = Counter();
1390
1391   if (message)
1392     printf("%s %.2f seconds\n", message,
1393            (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
1394
1395   counter[counter_nr][1] = Counter();
1396 }