rnd-20000718-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 <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;
338
339   if (s == NULL)
340     return NULL;
341
342   s_copy = checked_malloc(strlen(s) + 1);
343
344   strcpy(s_copy, s);
345   return s_copy;
346 }
347
348 char *getStringToLower(char *s)
349 {
350   char *s_copy = checked_malloc(strlen(s) + 1);
351   char *s_ptr = s_copy;
352
353   while (*s)
354     *s_ptr++ = tolower(*s++);
355   *s_ptr = '\0';
356
357   return s_copy;
358 }
359
360 void MarkTileDirty(int x, int y)
361 {
362   int xx = redraw_x1 + x;
363   int yy = redraw_y1 + y;
364
365   if (!redraw[xx][yy])
366     redraw_tiles++;
367
368   redraw[xx][yy] = TRUE;
369   redraw_mask |= REDRAW_TILES;
370 }
371
372 void SetBorderElement()
373 {
374   int x, y;
375
376   BorderElement = EL_LEERRAUM;
377
378   for(y=0; y<lev_fieldy && BorderElement == EL_LEERRAUM; y++)
379   {
380     for(x=0; x<lev_fieldx; x++)
381     {
382       if (!IS_MASSIVE(Feld[x][y]))
383         BorderElement = EL_BETON;
384
385       if (y != 0 && y != lev_fieldy - 1 && x != lev_fieldx - 1)
386         x = lev_fieldx - 2;
387     }
388   }
389 }
390
391 void GetOptions(char *argv[])
392 {
393   char **options_left = &argv[1];
394
395   /* initialize global program options */
396   options.display_name = NULL;
397   options.server_host = NULL;
398   options.server_port = 0;
399   options.ro_base_directory = RO_BASE_PATH;
400   options.rw_base_directory = RW_BASE_PATH;
401   options.level_directory = RO_BASE_PATH "/" LEVELS_DIRECTORY;
402   options.serveronly = FALSE;
403   options.network = FALSE;
404   options.verbose = FALSE;
405
406   while (*options_left)
407   {
408     char option_str[MAX_OPTION_LEN];
409     char *option = options_left[0];
410     char *next_option = options_left[1];
411     char *option_arg = NULL;
412     int option_len = strlen(option);
413
414     if (option_len >= MAX_OPTION_LEN)
415       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
416
417     strcpy(option_str, option);                 /* copy argument into buffer */
418     option = option_str;
419
420     if (strcmp(option, "--") == 0)              /* stop scanning arguments */
421       break;
422
423     if (strncmp(option, "--", 2) == 0)          /* treat '--' like '-' */
424       option++;
425
426     option_arg = strchr(option, '=');
427     if (option_arg == NULL)                     /* no '=' in option */
428       option_arg = next_option;
429     else
430     {
431       *option_arg++ = '\0';                     /* cut argument from option */
432       if (*option_arg == '\0')                  /* no argument after '=' */
433         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
434     }
435
436     option_len = strlen(option);
437
438     if (strcmp(option, "-") == 0)
439       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
440     else if (strncmp(option, "-help", option_len) == 0)
441     {
442       printf("Usage: %s [options] [server.name [port]]\n"
443              "Options:\n"
444              "  -d, --display machine:0       X server display\n"
445              "  -b, --basepath directory      alternative base directory\n"
446              "  -l, --level directory        alternative level directory\n"
447              "  -s, --serveronly              only start network server\n"
448              "  -n, --network                 network multiplayer game\n"
449              "  -v, --verbose                 verbose mode\n",
450              program_name);
451       exit(0);
452     }
453     else if (strncmp(option, "-display", option_len) == 0)
454     {
455       if (option_arg == NULL)
456         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
457
458       options.display_name = option_arg;
459       if (option_arg == next_option)
460         options_left++;
461     }
462     else if (strncmp(option, "-basepath", option_len) == 0)
463     {
464       if (option_arg == NULL)
465         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
466
467       /* this should be extended to separate options for ro and rw data */
468       options.ro_base_directory = option_arg;
469       options.rw_base_directory = option_arg;
470       if (option_arg == next_option)
471         options_left++;
472
473       /* adjust path for level directory accordingly */
474       options.level_directory =
475         getPath2(options.ro_base_directory, LEVELS_DIRECTORY);
476     }
477     else if (strncmp(option, "-levels", option_len) == 0)
478     {
479       if (option_arg == NULL)
480         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
481
482       options.level_directory = option_arg;
483       if (option_arg == next_option)
484         options_left++;
485     }
486     else if (strncmp(option, "-network", option_len) == 0)
487     {
488       options.network = TRUE;
489     }
490     else if (strncmp(option, "-serveronly", option_len) == 0)
491     {
492       options.serveronly = TRUE;
493     }
494     else if (strncmp(option, "-verbose", option_len) == 0)
495     {
496       options.verbose = TRUE;
497     }
498     else if (*option == '-')
499     {
500       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
501     }
502     else if (options.server_host == NULL)
503     {
504       options.server_host = *options_left;
505     }
506     else if (options.server_port == 0)
507     {
508       options.server_port = atoi(*options_left);
509       if (options.server_port < 1024)
510         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
511     }
512     else
513       Error(ERR_EXIT_HELP, "too many arguments");
514
515     options_left++;
516   }
517 }
518
519 void Error(int mode, char *format, ...)
520 {
521   char *process_name = "";
522   FILE *error = stderr;
523
524   /* display warnings only when running in verbose mode */
525   if (mode & ERR_WARN && !options.verbose)
526     return;
527
528 #ifdef MSDOS
529   if ((error = openErrorFile()) == NULL)
530   {
531     printf("Cannot write to error output file!\n");
532     CloseAllAndExit(1);
533   }
534 #endif
535
536   if (mode & ERR_SOUND_SERVER)
537     process_name = " sound server";
538   else if (mode & ERR_NETWORK_SERVER)
539     process_name = " network server";
540   else if (mode & ERR_NETWORK_CLIENT)
541     process_name = " network client **";
542
543   if (format)
544   {
545     va_list ap;
546
547     fprintf(error, "%s%s: ", program_name, process_name);
548
549     if (mode & ERR_WARN)
550       fprintf(error, "warning: ");
551
552     va_start(ap, format);
553     vfprintf(error, format, ap);
554     va_end(ap);
555   
556     fprintf(error, "\n");
557   }
558   
559   if (mode & ERR_HELP)
560     fprintf(error, "%s: Try option '--help' for more information.\n",
561             program_name);
562
563   if (mode & ERR_EXIT)
564     fprintf(error, "%s%s: aborting\n", program_name, process_name);
565
566   if (error != stderr)
567     fclose(error);
568
569   if (mode & ERR_EXIT)
570   {
571     if (mode & ERR_FROM_SERVER)
572       exit(1);                          /* child process: normal exit */
573     else
574       CloseAllAndExit(1);               /* main process: clean up stuff */
575   }
576 }
577
578 void *checked_malloc(unsigned long size)
579 {
580   void *ptr;
581
582   ptr = malloc(size);
583
584   if (ptr == NULL)
585     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
586
587   return ptr;
588 }
589
590 void *checked_calloc(unsigned long size)
591 {
592   void *ptr;
593
594   ptr = calloc(1, size);
595
596   if (ptr == NULL)
597     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
598
599   return ptr;
600 }
601
602 short getFile16BitInteger(FILE *file, int byte_order)
603 {
604   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
605     return ((fgetc(file) <<  8) |
606             (fgetc(file) <<  0));
607   else           /* BYTE_ORDER_LITTLE_ENDIAN */
608     return ((fgetc(file) <<  0) |
609             (fgetc(file) <<  8));
610 }
611
612 void putFile16BitInteger(FILE *file, short value, int byte_order)
613 {
614   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
615   {
616     fputc((value >>  8) & 0xff, file);
617     fputc((value >>  0) & 0xff, file);
618   }
619   else           /* BYTE_ORDER_LITTLE_ENDIAN */
620   {
621     fputc((value >>  0) & 0xff, file);
622     fputc((value >>  8) & 0xff, file);
623   }
624 }
625
626 int getFile32BitInteger(FILE *file, int byte_order)
627 {
628   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
629     return ((fgetc(file) << 24) |
630             (fgetc(file) << 16) |
631             (fgetc(file) <<  8) |
632             (fgetc(file) <<  0));
633   else           /* BYTE_ORDER_LITTLE_ENDIAN */
634     return ((fgetc(file) <<  0) |
635             (fgetc(file) <<  8) |
636             (fgetc(file) << 16) |
637             (fgetc(file) << 24));
638 }
639
640 void putFile32BitInteger(FILE *file, int value, int byte_order)
641 {
642   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
643   {
644     fputc((value >> 24) & 0xff, file);
645     fputc((value >> 16) & 0xff, file);
646     fputc((value >>  8) & 0xff, file);
647     fputc((value >>  0) & 0xff, file);
648   }
649   else           /* BYTE_ORDER_LITTLE_ENDIAN */
650   {
651     fputc((value >>  0) & 0xff, file);
652     fputc((value >>  8) & 0xff, file);
653     fputc((value >> 16) & 0xff, file);
654     fputc((value >> 24) & 0xff, file);
655   }
656 }
657
658 void getFileChunk(FILE *file, char *chunk_buffer, int *chunk_length,
659                   int byte_order)
660 {
661   const int chunk_identifier_length = 4;
662
663   /* read chunk identifier */
664   fgets(chunk_buffer, chunk_identifier_length + 1, file);
665
666   /* read chunk length */
667   *chunk_length = getFile32BitInteger(file, byte_order);
668 }
669
670 void putFileChunk(FILE *file, char *chunk_name, int chunk_length,
671                   int byte_order)
672 {
673   /* write chunk identifier */
674   fputs(chunk_name, file);
675
676   /* write chunk length */
677   putFile32BitInteger(file, chunk_length, byte_order);
678 }
679
680 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
681 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
682 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  2
683
684 void translate_keyname(KeySym *keysym, char **x11name, char **name, int mode)
685 {
686   static struct
687   {
688     KeySym keysym;
689     char *x11name;
690     char *name;
691   } translate_key[] =
692   {
693     /* normal cursor keys */
694     { XK_Left,          "XK_Left",              "cursor left" },
695     { XK_Right,         "XK_Right",             "cursor right" },
696     { XK_Up,            "XK_Up",                "cursor up" },
697     { XK_Down,          "XK_Down",              "cursor down" },
698
699     /* keypad cursor keys */
700 #ifdef XK_KP_Left
701     { XK_KP_Left,       "XK_KP_Left",           "keypad left" },
702     { XK_KP_Right,      "XK_KP_Right",          "keypad right" },
703     { XK_KP_Up,         "XK_KP_Up",             "keypad up" },
704     { XK_KP_Down,       "XK_KP_Down",           "keypad down" },
705 #endif
706
707     /* other keypad keys */
708 #ifdef XK_KP_Enter
709     { XK_KP_Enter,      "XK_KP_Enter",          "keypad enter" },
710     { XK_KP_Add,        "XK_KP_Add",            "keypad +" },
711     { XK_KP_Subtract,   "XK_KP_Subtract",       "keypad -" },
712     { XK_KP_Multiply,   "XK_KP_Multiply",       "keypad mltply" },
713     { XK_KP_Divide,     "XK_KP_Divide",         "keypad /" },
714     { XK_KP_Separator,  "XK_KP_Separator",      "keypad ," },
715 #endif
716
717     /* modifier keys */
718     { XK_Shift_L,       "XK_Shift_L",           "left shift" },
719     { XK_Shift_R,       "XK_Shift_R",           "right shift" },
720     { XK_Control_L,     "XK_Control_L",         "left control" },
721     { XK_Control_R,     "XK_Control_R",         "right control" },
722     { XK_Meta_L,        "XK_Meta_L",            "left meta" },
723     { XK_Meta_R,        "XK_Meta_R",            "right meta" },
724     { XK_Alt_L,         "XK_Alt_L",             "left alt" },
725     { XK_Alt_R,         "XK_Alt_R",             "right alt" },
726     { XK_Mode_switch,   "XK_Mode_switch",       "mode switch" },
727     { XK_Multi_key,     "XK_Multi_key",         "multi key" },
728
729     /* some special keys */
730     { XK_BackSpace,     "XK_BackSpace",         "backspace" },
731     { XK_Delete,        "XK_Delete",            "delete" },
732     { XK_Insert,        "XK_Insert",            "insert" },
733     { XK_Tab,           "XK_Tab",               "tab" },
734     { XK_Home,          "XK_Home",              "home" },
735     { XK_End,           "XK_End",               "end" },
736     { XK_Page_Up,       "XK_Page_Up",           "page up" },
737     { XK_Page_Down,     "XK_Page_Down",         "page down" },
738
739
740     /* ASCII 0x20 to 0x40 keys (except numbers) */
741     { XK_space,         "XK_space",             "space" },
742     { XK_exclam,        "XK_exclam",            "!" },
743     { XK_quotedbl,      "XK_quotedbl",          "\"" },
744     { XK_numbersign,    "XK_numbersign",        "#" },
745     { XK_dollar,        "XK_dollar",            "$" },
746     { XK_percent,       "XK_percent",           "%" },
747     { XK_ampersand,     "XK_ampersand",         "&" },
748     { XK_apostrophe,    "XK_apostrophe",        "'" },
749     { XK_parenleft,     "XK_parenleft",         "(" },
750     { XK_parenright,    "XK_parenright",        ")" },
751     { XK_asterisk,      "XK_asterisk",          "*" },
752     { XK_plus,          "XK_plus",              "+" },
753     { XK_comma,         "XK_comma",             "," },
754     { XK_minus,         "XK_minus",             "-" },
755     { XK_period,        "XK_period",            "." },
756     { XK_slash,         "XK_slash",             "/" },
757     { XK_colon,         "XK_colon",             ":" },
758     { XK_semicolon,     "XK_semicolon",         ";" },
759     { XK_less,          "XK_less",              "<" },
760     { XK_equal,         "XK_equal",             "=" },
761     { XK_greater,       "XK_greater",           ">" },
762     { XK_question,      "XK_question",          "?" },
763     { XK_at,            "XK_at",                "@" },
764
765     /* more ASCII keys */
766     { XK_bracketleft,   "XK_bracketleft",       "[" },
767     { XK_backslash,     "XK_backslash",         "backslash" },
768     { XK_bracketright,  "XK_bracketright",      "]" },
769     { XK_asciicircum,   "XK_asciicircum",       "circumflex" },
770     { XK_underscore,    "XK_underscore",        "_" },
771     { XK_grave,         "XK_grave",             "grave" },
772     { XK_quoteleft,     "XK_quoteleft",         "quote left" },
773     { XK_braceleft,     "XK_braceleft",         "brace left" },
774     { XK_bar,           "XK_bar",               "bar" },
775     { XK_braceright,    "XK_braceright",        "brace right" },
776     { XK_asciitilde,    "XK_asciitilde",        "ascii tilde" },
777
778     /* special (non-ASCII) keys */
779     { XK_Adiaeresis,    "XK_Adiaeresis",        "Ă„" },
780     { XK_Odiaeresis,    "XK_Odiaeresis",        "Ă–" },
781     { XK_Udiaeresis,    "XK_Udiaeresis",        "Ăœ" },
782     { XK_adiaeresis,    "XK_adiaeresis",        "ä" },
783     { XK_odiaeresis,    "XK_odiaeresis",        "ö" },
784     { XK_udiaeresis,    "XK_udiaeresis",        "Ă¼" },
785     { XK_ssharp,        "XK_ssharp",            "sharp s" },
786
787     /* end-of-array identifier */
788     { 0,                NULL,                   NULL }
789   };
790
791   int i;
792
793   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
794   {
795     static char name_buffer[30];
796     KeySym key = *keysym;
797
798     if (key >= XK_A && key <= XK_Z)
799       sprintf(name_buffer, "%c", 'A' + (char)(key - XK_A));
800     else if (key >= XK_a && key <= XK_z)
801       sprintf(name_buffer, "%c", 'a' + (char)(key - XK_a));
802     else if (key >= XK_0 && key <= XK_9)
803       sprintf(name_buffer, "%c", '0' + (char)(key - XK_0));
804     else if (key >= XK_KP_0 && key <= XK_KP_9)
805       sprintf(name_buffer, "keypad %c", '0' + (char)(key - XK_KP_0));
806     else if (key >= XK_F1 && key <= XK_F24)
807       sprintf(name_buffer, "function F%d", (int)(key - XK_F1 + 1));
808     else if (key == KEY_UNDEFINDED)
809       strcpy(name_buffer, "(undefined)");
810     else
811     {
812       i = 0;
813
814       do
815       {
816         if (key == translate_key[i].keysym)
817         {
818           strcpy(name_buffer, translate_key[i].name);
819           break;
820         }
821       }
822       while (translate_key[++i].name);
823
824       if (!translate_key[i].name)
825         strcpy(name_buffer, "(unknown)");
826     }
827
828     *name = name_buffer;
829   }
830   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
831   {
832     static char name_buffer[30];
833     KeySym key = *keysym;
834
835     if (key >= XK_A && key <= XK_Z)
836       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - XK_A));
837     else if (key >= XK_a && key <= XK_z)
838       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - XK_a));
839     else if (key >= XK_0 && key <= XK_9)
840       sprintf(name_buffer, "XK_%c", '0' + (char)(key - XK_0));
841     else if (key >= XK_KP_0 && key <= XK_KP_9)
842       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - XK_KP_0));
843     else if (key >= XK_F1 && key <= XK_F24)
844       sprintf(name_buffer, "XK_F%d", (int)(key - XK_F1 + 1));
845     else if (key == KEY_UNDEFINDED)
846       strcpy(name_buffer, "[undefined]");
847     else
848     {
849       i = 0;
850
851       do
852       {
853         if (key == translate_key[i].keysym)
854         {
855           strcpy(name_buffer, translate_key[i].x11name);
856           break;
857         }
858       }
859       while (translate_key[++i].x11name);
860
861       if (!translate_key[i].x11name)
862         sprintf(name_buffer, "0x%04lx", (unsigned long)key);
863     }
864
865     *x11name = name_buffer;
866   }
867   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
868   {
869     KeySym key = XK_VoidSymbol;
870     char *name_ptr = *x11name;
871
872     if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
873     {
874       char c = name_ptr[3];
875
876       if (c >= 'A' && c <= 'Z')
877         key = XK_A + (KeySym)(c - 'A');
878       else if (c >= 'a' && c <= 'z')
879         key = XK_a + (KeySym)(c - 'a');
880       else if (c >= '0' && c <= '9')
881         key = XK_0 + (KeySym)(c - '0');
882     }
883     else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
884     {
885       char c = name_ptr[6];
886
887       if (c >= '0' && c <= '9')
888         key = XK_0 + (KeySym)(c - '0');
889     }
890     else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
891     {
892       char c1 = name_ptr[4];
893       char c2 = name_ptr[5];
894       int d = 0;
895
896       if ((c1 >= '0' && c1 <= '9') &&
897           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
898         d = atoi(&name_ptr[4]);
899
900       if (d >=1 && d <= 24)
901         key = XK_F1 + (KeySym)(d - 1);
902     }
903     else if (strncmp(name_ptr, "XK_", 3) == 0)
904     {
905       i = 0;
906
907       do
908       {
909         if (strcmp(name_ptr, translate_key[i].x11name) == 0)
910         {
911           key = translate_key[i].keysym;
912           break;
913         }
914       }
915       while (translate_key[++i].x11name);
916     }
917     else if (strncmp(name_ptr, "0x", 2) == 0)
918     {
919       unsigned long value = 0;
920
921       name_ptr += 2;
922
923       while (name_ptr)
924       {
925         char c = *name_ptr++;
926         int d = -1;
927
928         if (c >= '0' && c <= '9')
929           d = (int)(c - '0');
930         else if (c >= 'a' && c <= 'f')
931           d = (int)(c - 'a' + 10);
932         else if (c >= 'A' && c <= 'F')
933           d = (int)(c - 'A' + 10);
934
935         if (d == -1)
936         {
937           value = -1;
938           break;
939         }
940
941         value = value * 16 + d;
942       }
943
944       if (value != -1)
945         key = (KeySym)value;
946     }
947
948     *keysym = key;
949   }
950 }
951
952 char *getKeyNameFromKeySym(KeySym keysym)
953 {
954   char *name;
955
956   translate_keyname(&keysym, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
957   return name;
958 }
959
960 char *getX11KeyNameFromKeySym(KeySym keysym)
961 {
962   char *x11name;
963
964   translate_keyname(&keysym, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
965   return x11name;
966 }
967
968 KeySym getKeySymFromX11KeyName(char *x11name)
969 {
970   KeySym keysym;
971
972   translate_keyname(&keysym, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
973   return keysym;
974 }
975
976 char getCharFromKeySym(KeySym keysym)
977 {
978   char *keyname = getKeyNameFromKeySym(keysym);
979   char letter = 0;
980
981   if (strlen(keyname) == 1)
982     letter = keyname[0];
983   else if (strcmp(keyname, "space") == 0)
984     letter = ' ';
985   else if (strcmp(keyname, "circumflex") == 0)
986     letter = '^';
987
988   return letter;
989 }
990
991 #define TRANSLATE_JOYSYMBOL_TO_JOYNAME  0
992 #define TRANSLATE_JOYNAME_TO_JOYSYMBOL  1
993
994 void translate_joyname(int *joysymbol, char **name, int mode)
995 {
996   static struct
997   {
998     int joysymbol;
999     char *name;
1000   } translate_joy[] =
1001   {
1002     { JOY_LEFT,         "joystick_left" },
1003     { JOY_RIGHT,        "joystick_right" },
1004     { JOY_UP,           "joystick_up" },
1005     { JOY_DOWN,         "joystick_down" },
1006     { JOY_BUTTON_1,     "joystick_button_1" },
1007     { JOY_BUTTON_2,     "joystick_button_2" },
1008   };
1009
1010   int i;
1011
1012   if (mode == TRANSLATE_JOYSYMBOL_TO_JOYNAME)
1013   {
1014     *name = "[undefined]";
1015
1016     for (i=0; i<6; i++)
1017     {
1018       if (*joysymbol == translate_joy[i].joysymbol)
1019       {
1020         *name = translate_joy[i].name;
1021         break;
1022       }
1023     }
1024   }
1025   else if (mode == TRANSLATE_JOYNAME_TO_JOYSYMBOL)
1026   {
1027     *joysymbol = 0;
1028
1029     for (i=0; i<6; i++)
1030     {
1031       if (strcmp(*name, translate_joy[i].name) == 0)
1032       {
1033         *joysymbol = translate_joy[i].joysymbol;
1034         break;
1035       }
1036     }
1037   }
1038 }
1039
1040 char *getJoyNameFromJoySymbol(int joysymbol)
1041 {
1042   char *name;
1043
1044   translate_joyname(&joysymbol, &name, TRANSLATE_JOYSYMBOL_TO_JOYNAME);
1045   return name;
1046 }
1047
1048 int getJoySymbolFromJoyName(char *name)
1049 {
1050   int joysymbol;
1051
1052   translate_joyname(&joysymbol, &name, TRANSLATE_JOYNAME_TO_JOYSYMBOL);
1053   return joysymbol;
1054 }
1055
1056 int getJoystickNrFromDeviceName(char *device_name)
1057 {
1058   char c;
1059   int joystick_nr = 0;
1060
1061   if (device_name == NULL || device_name[0] == '\0')
1062     return 0;
1063
1064   c = device_name[strlen(device_name) - 1];
1065
1066   if (c >= '0' && c <= '9')
1067     joystick_nr = (int)(c - '0');
1068
1069   if (joystick_nr < 0 || joystick_nr >= MAX_PLAYERS)
1070     joystick_nr = 0;
1071
1072   return joystick_nr;
1073 }
1074
1075 /* ------------------------------------------------------------------------- */
1076 /* some functions to handle lists of level directories                       */
1077 /* ------------------------------------------------------------------------- */
1078
1079 struct LevelDirInfo *newLevelDirInfo()
1080 {
1081   return checked_calloc(sizeof(struct LevelDirInfo));
1082 }
1083
1084 void pushLevelDirInfo(struct LevelDirInfo **node_first,
1085                       struct LevelDirInfo *node_new)
1086 {
1087   node_new->next = *node_first;
1088   *node_first = node_new;
1089 }
1090
1091 int numLevelDirInfo(struct LevelDirInfo *node)
1092 {
1093   int num = 0;
1094
1095   while (node)
1096   {
1097     num++;
1098     node = node->next;
1099   }
1100
1101   return num;
1102 }
1103
1104 boolean validLevelSeries(struct LevelDirInfo *node)
1105 {
1106   return (node != NULL && !node->node_group && !node->parent_link);
1107 }
1108
1109 struct LevelDirInfo *getFirstValidLevelSeries(struct LevelDirInfo *node)
1110 {
1111   if (node == NULL)             /* start with first level directory entry */
1112     return getFirstValidLevelSeries(leveldir_first);
1113   else if (node->node_group)    /* enter level group (step down into tree) */
1114     return getFirstValidLevelSeries(node->node_group);
1115   else if (node->parent_link)   /* skip start entry of level group */
1116   {
1117     if (node->next)             /* get first real level series entry */
1118       return getFirstValidLevelSeries(node->next);
1119     else                        /* leave empty level group and go on */
1120       return getFirstValidLevelSeries(node->node_parent->next);
1121   }
1122   else                          /* this seems to be a regular level series */
1123     return node;
1124 }
1125
1126 struct LevelDirInfo *getLevelDirInfoFirstGroupEntry(struct LevelDirInfo *node)
1127 {
1128   if (node == NULL)
1129     return NULL;
1130
1131   if (node->node_parent == NULL)                /* top level group */
1132     return leveldir_first;
1133   else                                          /* sub level group */
1134     return node->node_parent->node_group;
1135 }
1136
1137 int numLevelDirInfoInGroup(struct LevelDirInfo *node)
1138 {
1139   return numLevelDirInfo(getLevelDirInfoFirstGroupEntry(node));
1140 }
1141
1142 int posLevelDirInfo(struct LevelDirInfo *node)
1143 {
1144   struct LevelDirInfo *node_cmp = getLevelDirInfoFirstGroupEntry(node);
1145   int pos = 0;
1146
1147   while (node_cmp)
1148   {
1149     if (node_cmp == node)
1150       return pos;
1151
1152     pos++;
1153     node_cmp = node_cmp->next;
1154   }
1155
1156   return 0;
1157 }
1158
1159 struct LevelDirInfo *getLevelDirInfoFromPos(struct LevelDirInfo *node, int pos)
1160 {
1161   struct LevelDirInfo *node_default = node;
1162   int pos_cmp = 0;
1163
1164   while (node)
1165   {
1166     if (pos_cmp == pos)
1167       return node;
1168
1169     pos_cmp++;
1170     node = node->next;
1171   }
1172
1173   return node_default;
1174 }
1175
1176 struct LevelDirInfo *getLevelDirInfoFromFilenameExt(struct LevelDirInfo *node,
1177                                                     char *filename)
1178 {
1179   if (filename == NULL)
1180     return NULL;
1181
1182   while (node)
1183   {
1184     if (node->node_group)
1185     {
1186       struct LevelDirInfo *node_group;
1187
1188       node_group = getLevelDirInfoFromFilenameExt(node->node_group, filename);
1189
1190       if (node_group)
1191         return node_group;
1192     }
1193     else if (!node->parent_link)
1194     {
1195       if (strcmp(filename, node->filename) == 0)
1196         return node;
1197     }
1198
1199     node = node->next;
1200   }
1201
1202   return NULL;
1203 }
1204
1205 struct LevelDirInfo *getLevelDirInfoFromFilename(char *filename)
1206 {
1207   return getLevelDirInfoFromFilenameExt(leveldir_first, filename);
1208 }
1209
1210 void dumpLevelDirInfo(struct LevelDirInfo *node, int depth)
1211 {
1212   int i;
1213
1214   while (node)
1215   {
1216     for (i=0; i<depth * 3; i++)
1217       printf(" ");
1218
1219     printf("filename == '%s'\n", node->filename);
1220
1221     if (node->node_group != NULL)
1222       dumpLevelDirInfo(node->node_group, depth + 1);
1223
1224     node = node->next;
1225   }
1226 }
1227
1228 void sortLevelDirInfo(struct LevelDirInfo **node_first,
1229                       int (*compare_function)(const void *, const void *))
1230 {
1231   int num_nodes = numLevelDirInfo(*node_first);
1232   struct LevelDirInfo **sort_array;
1233   struct LevelDirInfo *node = *node_first;
1234   int i = 0;
1235
1236   if (num_nodes == 0)
1237     return;
1238
1239   /* allocate array for sorting structure pointers */
1240   sort_array = checked_calloc(num_nodes * sizeof(struct LevelDirInfo *));
1241
1242   /* writing structure pointers to sorting array */
1243   while (i < num_nodes && node)         /* double boundary check... */
1244   {
1245     sort_array[i] = node;
1246
1247     i++;
1248     node = node->next;
1249   }
1250
1251   /* sorting the structure pointers in the sorting array */
1252   qsort(sort_array, num_nodes, sizeof(struct LevelDirInfo *),
1253         compare_function);
1254
1255   /* update the linkage of list elements with the sorted node array */
1256   for (i=0; i<num_nodes - 1; i++)
1257     sort_array[i]->next = sort_array[i + 1];
1258   sort_array[num_nodes - 1]->next = NULL;
1259
1260   /* update the linkage of the main list anchor pointer */
1261   *node_first = sort_array[0];
1262
1263   free(sort_array);
1264
1265   /* now recursively sort the level group structures */
1266   node = *node_first;
1267   while (node)
1268   {
1269     if (node->node_group != NULL)
1270       sortLevelDirInfo(&node->node_group, compare_function);
1271
1272     node = node->next;
1273   }
1274 }
1275
1276
1277 /* ------------------------------------------------------------------------- */
1278 /* the following is only for debugging purpose and normally not used         */
1279 /* ------------------------------------------------------------------------- */
1280
1281 #define DEBUG_NUM_TIMESTAMPS    3
1282
1283 void debug_print_timestamp(int counter_nr, char *message)
1284 {
1285   static long counter[DEBUG_NUM_TIMESTAMPS][2];
1286
1287   if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
1288     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
1289
1290   counter[counter_nr][0] = Counter();
1291
1292   if (message)
1293     printf("%s %.2f seconds\n", message,
1294            (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
1295
1296   counter[counter_nr][1] = Counter();
1297 }