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