19c90ac508010a6cc72d3b5c9a30e104294bceda
[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
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 char *int2str(int number, int size)
171 {
172   static char s[40];
173
174   if (size > 20)
175     size = 20;
176
177   if (size)
178   {
179     sprintf(s, "                    %09d", number);
180     return &s[strlen(s) - size];
181   }
182   else
183   {
184     sprintf(s, "%d", number);
185     return s;
186   }
187 }
188
189 unsigned int SimpleRND(unsigned int max)
190 {
191   static unsigned long root = 654321;
192   struct timeval current_time;
193
194   gettimeofday(&current_time,NULL);
195   root = root * 4253261 + current_time.tv_sec + current_time.tv_usec;
196   return (root % max);
197 }
198
199 #ifdef DEBUG
200 static unsigned int last_RND_value = 0;
201
202 unsigned int last_RND()
203 {
204   return last_RND_value;
205 }
206 #endif
207
208 unsigned int RND(unsigned int max)
209 {
210 #ifdef DEBUG
211   return (last_RND_value = random_linux_libc() % max);
212 #else
213   return (random_linux_libc() % max);
214 #endif
215 }
216
217 unsigned int InitRND(long seed)
218 {
219   struct timeval current_time;
220
221   if (seed == NEW_RANDOMIZE)
222   {
223     gettimeofday(&current_time,NULL);
224     srandom_linux_libc((unsigned int) current_time.tv_usec);
225     return (unsigned int)current_time.tv_usec;
226   }
227   else
228   {
229     srandom_linux_libc((unsigned int) seed);
230     return (unsigned int)seed;
231   }
232 }
233
234 char *getLoginName()
235 {
236   struct passwd *pwd;
237
238   if (!(pwd = getpwuid(getuid())))
239     return "ANONYMOUS";
240   else
241     return pwd->pw_name;
242 }
243
244 char *getHomeDir()
245 {
246 #ifndef MSDOS
247   static char *home_dir = NULL;
248
249   if (!home_dir)
250   {
251     if (!(home_dir = getenv("HOME")))
252     {
253       struct passwd *pwd;
254
255       if ((pwd = getpwuid(getuid())))
256         home_dir = pwd->pw_dir;
257       else
258         home_dir = ".";
259     }
260   }
261
262   return home_dir;
263 #else
264   return ".";
265 #endif
266 }
267
268 char *getPath2(char *path1, char *path2)
269 {
270   char *complete_path = checked_malloc(strlen(path1) + 1 +
271                                        strlen(path2) + 1);
272
273   sprintf(complete_path, "%s/%s", path1, path2);
274   return complete_path;
275 }
276
277 char *getPath3(char *path1, char *path2, char *path3)
278 {
279   char *complete_path = checked_malloc(strlen(path1) + 1 +
280                                        strlen(path2) + 1 +
281                                        strlen(path3) + 1);
282
283   sprintf(complete_path, "%s/%s/%s", path1, path2, path3);
284   return complete_path;
285 }
286
287 char *getStringCopy(char *s)
288 {
289   char *s_copy = checked_malloc(strlen(s) + 1);
290
291   strcpy(s_copy, s);
292   return s_copy;
293 }
294
295 char *getStringToLower(char *s)
296 {
297   char *s_copy = checked_malloc(strlen(s) + 1);
298   char *s_ptr = s_copy;
299
300   while (*s)
301     *s_ptr++ = tolower(*s++);
302
303   return s_copy;
304 }
305
306 void MarkTileDirty(int x, int y)
307 {
308   int xx = redraw_x1 + x;
309   int yy = redraw_y1 + y;
310
311   if (!redraw[xx][yy])
312     redraw_tiles++;
313
314   redraw[xx][yy] = TRUE;
315   redraw_mask |= REDRAW_TILES;
316 }
317
318 void GetOptions(char *argv[])
319 {
320   char **options_left = &argv[1];
321
322   /* initialize global program options */
323   options.display_name = NULL;
324   options.server_host = NULL;
325   options.server_port = 0;
326   options.base_directory = BASE_PATH;
327   options.level_directory = BASE_PATH "/" LEVELS_DIRECTORY;
328   options.serveronly = FALSE;
329   options.network = FALSE;
330   options.verbose = FALSE;
331
332   while (*options_left)
333   {
334     char option_str[MAX_OPTION_LEN];
335     char *option = options_left[0];
336     char *next_option = options_left[1];
337     char *option_arg = NULL;
338     int option_len = strlen(option);
339
340     strcpy(option_str, option);                 /* copy argument into buffer */
341     option = option_str;
342
343     if (strcmp(option, "--") == 0)              /* stop scanning arguments */
344       break;
345
346     if (option_len >= MAX_OPTION_LEN)
347       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
348
349     if (strncmp(option, "--", 2) == 0)          /* treat '--' like '-' */
350       option++;
351
352     option_arg = strchr(option, '=');
353     if (option_arg == NULL)                     /* no '=' in option */
354       option_arg = next_option;
355     else
356     {
357       *option_arg++ = '\0';                     /* cut argument from option */
358       if (*option_arg == '\0')                  /* no argument after '=' */
359         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
360     }
361
362     option_len = strlen(option);
363
364     if (strcmp(option, "-") == 0)
365       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
366     else if (strncmp(option, "-help", option_len) == 0)
367     {
368       printf("Usage: %s [options] [server.name [port]]\n"
369              "Options:\n"
370              "  -d, --display machine:0       X server display\n"
371              "  -b, --basepath directory      alternative base directory\n"
372              "  -l, --levels directory        alternative level directory\n"
373              "  -s, --serveronly              only start network server\n"
374              "  -n, --network                 network multiplayer game\n"
375              "  -v, --verbose                 verbose mode\n",
376              program_name);
377       exit(0);
378     }
379     else if (strncmp(option, "-display", option_len) == 0)
380     {
381       if (option_arg == NULL)
382         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
383
384       options.display_name = option_arg;
385       if (option_arg == next_option)
386         options_left++;
387
388       printf("--display == '%s'\n", options.display_name);
389     }
390     else if (strncmp(option, "-basepath", option_len) == 0)
391     {
392       if (option_arg == NULL)
393         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
394
395       options.base_directory = option_arg;
396       if (option_arg == next_option)
397         options_left++;
398
399       printf("--basepath == '%s'\n", options.base_directory);
400
401       /* adjust path for level directory accordingly */
402       options.level_directory =
403         getPath2(options.base_directory, LEVELS_DIRECTORY);
404     }
405     else if (strncmp(option, "-levels", option_len) == 0)
406     {
407       if (option_arg == NULL)
408         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
409
410       options.level_directory = option_arg;
411       if (option_arg == next_option)
412         options_left++;
413
414       printf("--levels == '%s'\n", options.level_directory);
415     }
416     else if (strncmp(option, "-network", option_len) == 0)
417     {
418       printf("--network\n");
419
420       options.network = TRUE;
421     }
422     else if (strncmp(option, "-serveronly", option_len) == 0)
423     {
424       printf("--serveronly\n");
425
426       options.serveronly = TRUE;
427     }
428     else if (strncmp(option, "-verbose", option_len) == 0)
429     {
430       printf("--verbose\n");
431
432       options.verbose = TRUE;
433     }
434     else if (*option == '-')
435       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
436     else if (options.server_host == NULL)
437     {
438       options.server_host = *options_left;
439
440       printf("server.name == '%s'\n", options.server_host);
441     }
442     else if (options.server_port == 0)
443     {
444       options.server_port = atoi(*options_left);
445       if (options.server_port < 1024)
446         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
447
448       printf("port == %d\n", options.server_port);
449     }
450     else
451       Error(ERR_EXIT_HELP, "too many arguments");
452
453     options_left++;
454   }
455 }
456
457 void Error(int mode, char *format, ...)
458 {
459   char *process_name = "";
460
461   if (mode & ERR_SOUND_SERVER)
462     process_name = " sound server";
463   else if (mode & ERR_NETWORK_SERVER)
464     process_name = " network server";
465   else if (mode & ERR_NETWORK_CLIENT)
466     process_name = " network client **";
467
468   if (format)
469   {
470     va_list ap;
471
472     fprintf(stderr, "%s%s: ", program_name, process_name);
473
474     if (mode & ERR_WARN)
475       fprintf(stderr, "warning: ");
476
477     va_start(ap, format);
478     vfprintf(stderr, format, ap);
479     va_end(ap);
480   
481     fprintf(stderr, "\n");
482   }
483   
484   if (mode & ERR_HELP)
485     fprintf(stderr, "%s: Try option '--help' for more information.\n",
486             program_name);
487
488   if (mode & ERR_EXIT)
489   {
490     fprintf(stderr, "%s%s: aborting\n", program_name, process_name);
491
492     if (mode & ERR_FROM_SERVER)
493       exit(1);                          /* child process: normal exit */
494     else
495       CloseAllAndExit(1);               /* main process: clean up stuff */
496   }
497 }
498
499 void *checked_malloc(unsigned long size)
500 {
501   void *ptr;
502
503   ptr = malloc(size);
504
505   if (ptr == NULL)
506     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
507
508   return ptr;
509 }
510
511 void *checked_calloc(unsigned long size)
512 {
513   void *ptr;
514
515   ptr = calloc(1, size);
516
517   if (ptr == NULL)
518     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
519
520   return ptr;
521 }
522
523 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
524 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
525 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  2
526
527 void translate_keyname(KeySym *keysym, char **x11name, char **name, int mode)
528 {
529   static struct
530   {
531     KeySym keysym;
532     char *x11name;
533     char *name;
534   } translate_key[] =
535   {
536     /* normal cursor keys */
537     { XK_Left,          "XK_Left",              "cursor left" },
538     { XK_Right,         "XK_Right",             "cursor right" },
539     { XK_Up,            "XK_Up",                "cursor up" },
540     { XK_Down,          "XK_Down",              "cursor down" },
541
542     /* keypad cursor keys */
543 #ifdef XK_KP_Left
544     { XK_KP_Left,       "XK_KP_Left",           "keypad left" },
545     { XK_KP_Right,      "XK_KP_Right",          "keypad right" },
546     { XK_KP_Up,         "XK_KP_Up",             "keypad up" },
547     { XK_KP_Down,       "XK_KP_Down",           "keypad down" },
548 #endif
549
550     /* other keypad keys */
551 #ifdef XK_KP_Enter
552     { XK_KP_Enter,      "XK_KP_Enter",          "keypad enter" },
553     { XK_KP_Add,        "XK_KP_Add",            "keypad +" },
554     { XK_KP_Subtract,   "XK_KP_Subtract",       "keypad -" },
555     { XK_KP_Multiply,   "XK_KP_Multiply",       "keypad mltply" },
556     { XK_KP_Divide,     "XK_KP_Divide",         "keypad /" },
557     { XK_KP_Separator,  "XK_KP_Separator",      "keypad ," },
558 #endif
559
560     /* modifier keys */
561     { XK_Shift_L,       "XK_Shift_L",           "left shift" },
562     { XK_Shift_R,       "XK_Shift_R",           "right shift" },
563     { XK_Control_L,     "XK_Control_L",         "left control" },
564     { XK_Control_R,     "XK_Control_R",         "right control" },
565     { XK_Meta_L,        "XK_Meta_L",            "left meta" },
566     { XK_Meta_R,        "XK_Meta_R",            "right meta" },
567     { XK_Alt_L,         "XK_Alt_L",             "left alt" },
568     { XK_Alt_R,         "XK_Alt_R",             "right alt" },
569     { XK_Mode_switch,   "XK_Mode_switch",       "mode switch" },
570     { XK_Multi_key,     "XK_Multi_key",         "multi key" },
571
572     /* some special keys */
573     { XK_BackSpace,     "XK_BackSpace",         "backspace" },
574     { XK_Delete,        "XK_Delete",            "delete" },
575     { XK_Insert,        "XK_Insert",            "insert" },
576     { XK_Tab,           "XK_Tab",               "tab" },
577     { XK_Home,          "XK_Home",              "home" },
578     { XK_End,           "XK_End",               "end" },
579     { XK_Page_Up,       "XK_Page_Up",           "page up" },
580     { XK_Page_Down,     "XK_Page_Down",         "page down" },
581     { XK_space,         "XK_space",             "space" },
582
583     /* even more special keys */
584     { XK_adiaeresis,    "XK_adiaeresis",        "ä" },
585     { XK_odiaeresis,    "XK_odiaeresis",        "ö" },
586     { XK_udiaeresis,    "XK_udiaeresis",        "Ă¼" },
587     { XK_apostrophe,    "XK_apostrophe",        "'" },
588     { XK_plus,          "XK_plus",              "+" },
589     { XK_minus,         "XK_minus",             "-" },
590     { XK_comma,         "XK_comma",             "," },
591     { XK_period,        "XK_period",            "." },
592     { XK_numbersign,    "XK_numbersign",        "#" },
593     { XK_less,          "XK_less",              "less" },
594     { XK_greater,       "XK_greater",           "greater" },
595     { XK_asciicircum,   "XK_asciicircum",       "circumflex" },
596     { XK_ssharp,        "XK_ssharp",            "sharp s" },
597
598     /* end-of-array identifier */
599     { 0,                NULL,                   NULL }
600   };
601
602   int i;
603
604   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
605   {
606     static char name_buffer[30];
607     KeySym key = *keysym;
608
609     if (key >= XK_A && key <= XK_Z)
610       sprintf(name_buffer, "%c", 'A' + (char)(key - XK_A));
611     else if (key >= XK_a && key <= XK_z)
612       sprintf(name_buffer, "%c", 'a' + (char)(key - XK_a));
613     else if (key >= XK_0 && key <= XK_9)
614       sprintf(name_buffer, "%c", '0' + (char)(key - XK_0));
615     else if (key >= XK_KP_0 && key <= XK_KP_9)
616       sprintf(name_buffer, "keypad %c", '0' + (char)(key - XK_KP_0));
617     else if (key >= XK_F1 && key <= XK_F24)
618       sprintf(name_buffer, "function F%d", (int)(key - XK_F1 + 1));
619     else if (key == KEY_UNDEFINDED)
620       strcpy(name_buffer, "(undefined)");
621     else
622     {
623       i = 0;
624
625       do
626       {
627         if (key == translate_key[i].keysym)
628         {
629           strcpy(name_buffer, translate_key[i].name);
630           break;
631         }
632       }
633       while (translate_key[++i].name);
634
635       if (!translate_key[i].name)
636         strcpy(name_buffer, "(unknown)");
637     }
638
639     *name = name_buffer;
640   }
641   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
642   {
643     static char name_buffer[30];
644     KeySym key = *keysym;
645
646     if (key >= XK_A && key <= XK_Z)
647       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - XK_A));
648     else if (key >= XK_a && key <= XK_z)
649       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - XK_a));
650     else if (key >= XK_0 && key <= XK_9)
651       sprintf(name_buffer, "XK_%c", '0' + (char)(key - XK_0));
652     else if (key >= XK_KP_0 && key <= XK_KP_9)
653       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - XK_KP_0));
654     else if (key >= XK_F1 && key <= XK_F24)
655       sprintf(name_buffer, "XK_F%d", (int)(key - XK_F1 + 1));
656     else if (key == KEY_UNDEFINDED)
657       strcpy(name_buffer, "[undefined]");
658     else
659     {
660       i = 0;
661
662       do
663       {
664         if (key == translate_key[i].keysym)
665         {
666           strcpy(name_buffer, translate_key[i].x11name);
667           break;
668         }
669       }
670       while (translate_key[++i].x11name);
671
672       if (!translate_key[i].x11name)
673         sprintf(name_buffer, "0x%04lx", (unsigned long)key);
674     }
675
676     *x11name = name_buffer;
677   }
678   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
679   {
680     KeySym key = XK_VoidSymbol;
681     char *name_ptr = *x11name;
682
683     if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
684     {
685       char c = name_ptr[3];
686
687       if (c >= 'A' && c <= 'Z')
688         key = XK_A + (KeySym)(c - 'A');
689       else if (c >= 'a' && c <= 'z')
690         key = XK_a + (KeySym)(c - 'a');
691       else if (c >= '0' && c <= '9')
692         key = XK_0 + (KeySym)(c - '0');
693     }
694     else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
695     {
696       char c = name_ptr[6];
697
698       if (c >= '0' && c <= '9')
699         key = XK_0 + (KeySym)(c - '0');
700     }
701     else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
702     {
703       char c1 = name_ptr[4];
704       char c2 = name_ptr[5];
705       int d = 0;
706
707       if ((c1 >= '0' && c1 <= '9') &&
708           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
709         d = atoi(&name_ptr[4]);
710
711       if (d >=1 && d <= 24)
712         key = XK_F1 + (KeySym)(d - 1);
713     }
714     else if (strncmp(name_ptr, "XK_", 3) == 0)
715     {
716       i = 0;
717
718       do
719       {
720         if (strcmp(name_ptr, translate_key[i].x11name) == 0)
721         {
722           key = translate_key[i].keysym;
723           break;
724         }
725       }
726       while (translate_key[++i].x11name);
727     }
728     else if (strncmp(name_ptr, "0x", 2) == 0)
729     {
730       unsigned long value = 0;
731
732       name_ptr += 2;
733
734       while (name_ptr)
735       {
736         char c = *name_ptr++;
737         int d = -1;
738
739         if (c >= '0' && c <= '9')
740           d = (int)(c - '0');
741         else if (c >= 'a' && c <= 'f')
742           d = (int)(c - 'a' + 10);
743         else if (c >= 'A' && c <= 'F')
744           d = (int)(c - 'A' + 10);
745
746         if (d == -1)
747         {
748           value = -1;
749           break;
750         }
751
752         value = value * 16 + d;
753       }
754
755       if (value != -1)
756         key = (KeySym)value;
757     }
758
759     *keysym = key;
760   }
761 }
762
763 char *getKeyNameFromKeySym(KeySym keysym)
764 {
765   char *name;
766
767   translate_keyname(&keysym, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
768   return name;
769 }
770
771 char *getX11KeyNameFromKeySym(KeySym keysym)
772 {
773   char *x11name;
774
775   translate_keyname(&keysym, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
776   return x11name;
777 }
778
779 KeySym getKeySymFromX11KeyName(char *x11name)
780 {
781   KeySym keysym;
782
783   translate_keyname(&keysym, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
784   return keysym;
785 }
786
787 #define TRANSLATE_JOYSYMBOL_TO_JOYNAME  0
788 #define TRANSLATE_JOYNAME_TO_JOYSYMBOL  1
789
790 void translate_joyname(int *joysymbol, char **name, int mode)
791 {
792   static struct
793   {
794     int joysymbol;
795     char *name;
796   } translate_joy[] =
797   {
798     { JOY_LEFT,         "joystick_left" },
799     { JOY_RIGHT,        "joystick_right" },
800     { JOY_UP,           "joystick_up" },
801     { JOY_DOWN,         "joystick_down" },
802     { JOY_BUTTON_1,     "joystick_button_1" },
803     { JOY_BUTTON_2,     "joystick_button_2" },
804   };
805
806   int i;
807
808   if (mode == TRANSLATE_JOYSYMBOL_TO_JOYNAME)
809   {
810     *name = "[undefined]";
811
812     for (i=0; i<6; i++)
813     {
814       if (*joysymbol == translate_joy[i].joysymbol)
815       {
816         *name = translate_joy[i].name;
817         break;
818       }
819     }
820   }
821   else if (mode == TRANSLATE_JOYNAME_TO_JOYSYMBOL)
822   {
823     *joysymbol = 0;
824
825     for (i=0; i<6; i++)
826     {
827       if (strcmp(*name, translate_joy[i].name) == 0)
828       {
829         *joysymbol = translate_joy[i].joysymbol;
830         break;
831       }
832     }
833   }
834 }
835
836 char *getJoyNameFromJoySymbol(int joysymbol)
837 {
838   char *name;
839
840   translate_joyname(&joysymbol, &name, TRANSLATE_JOYSYMBOL_TO_JOYNAME);
841   return name;
842 }
843
844 int getJoySymbolFromJoyName(char *name)
845 {
846   int joysymbol;
847
848   translate_joyname(&joysymbol, &name, TRANSLATE_JOYNAME_TO_JOYSYMBOL);
849   return joysymbol;
850 }
851
852 /* the following is only for debugging purpose and normally not used */
853 #define DEBUG_NUM_TIMESTAMPS    3
854
855 void debug_print_timestamp(int counter_nr, char *message)
856 {
857   static long counter[DEBUG_NUM_TIMESTAMPS][2];
858
859   if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
860     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
861
862   counter[counter_nr][0] = Counter();
863
864   if (message)
865     printf("%s %.2f seconds\n", message,
866            (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
867
868   counter[counter_nr][1] = Counter();
869 }
870
871 void print_debug(char *s)
872 {
873   FILE *f;
874
875   if (!s)
876   {
877     if ((f = fopen("debug.asc", "w")) == NULL)
878     {
879       printf("Cannot write to debug file!\n");
880       exit(1);
881     }
882     fclose(f);
883     return;
884   }
885
886   if ((f = fopen("debug.asc", "a")) == NULL)
887   {
888     printf("Cannot append to debug file!\n");
889     exit(1);
890   }
891
892   fprintf(f, "%s\r\n", s);
893   fclose(f);
894 }