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