rnd-19990104-2
[rocksndiamonds.git] / src / files.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 *  files.h                                                 *
12 ***********************************************************/
13
14 #include <ctype.h>
15 #include <dirent.h>
16 #include <sys/stat.h>
17 #include <unistd.h>
18
19 #include "files.h"
20 #include "tools.h"
21 #include "misc.h"
22 #include "tape.h"
23 #include "joystick.h"
24
25 #define MAX_FILENAME_LEN        256     /* maximal filename length */
26 #define MAX_LINE_LEN            1000    /* maximal input line length */
27 #define CHUNK_ID_LEN            4       /* IFF style chunk id length */
28 #define LEVEL_HEADER_SIZE       80      /* size of level file header */
29 #define LEVEL_HEADER_UNUSED     18      /* unused level header bytes */
30 #define TAPE_HEADER_SIZE        20      /* size of tape file header */
31 #define TAPE_HEADER_UNUSED      7       /* unused tape header bytes */
32 #define FILE_VERSION_1_0        10      /* old 1.0 file version */
33 #define FILE_VERSION_1_2        12      /* actual file version */
34
35 /* file identifier strings */
36 #define LEVEL_COOKIE            "ROCKSNDIAMONDS_LEVEL_FILE_VERSION_1.2"
37 #define SCORE_COOKIE            "ROCKSNDIAMONDS_SCORE_FILE_VERSION_1.2"
38 #define TAPE_COOKIE             "ROCKSNDIAMONDS_TAPE_FILE_VERSION_1.2"
39 #define SETUP_COOKIE            "ROCKSNDIAMONDS_SETUP_FILE_VERSION_1.2"
40 #define LEVELSETUP_COOKIE       "ROCKSNDIAMONDS_LEVELSETUP_FILE_VERSION_1.2"
41 #define LEVELINFO_COOKIE        "ROCKSNDIAMONDS_LEVELINFO_FILE_VERSION_1.2"
42 /* old file identifiers for backward compatibility */
43 #define LEVEL_COOKIE_10         "ROCKSNDIAMONDS_LEVEL_FILE_VERSION_1.0"
44 #define TAPE_COOKIE_10          "ROCKSNDIAMONDS_LEVELREC_FILE_VERSION_1.0"
45
46 /* file names and filename extensions */
47 #ifndef MSDOS
48 #define USERDATA_DIRECTORY      ".rocksndiamonds"
49 #define SETUP_FILENAME          "setup.conf"
50 #define LEVELSETUP_FILENAME     "levelsetup.conf"
51 #define LEVELINFO_FILENAME      "levelinfo.conf"
52 #define LEVELFILE_EXTENSION     "level"
53 #define TAPEFILE_EXTENSION      "tape"
54 #define SCOREFILE_EXTENSION     "score"
55 #else
56 #define USERDATA_DIRECTORY      "userdata"
57 #define SETUP_FILENAME          "setup.cnf"
58 #define LEVELSETUP_FILENAME     "lvlsetup.cnf"
59 #define LEVELINFO_FILENAME      "lvlinfo.cnf"
60 #define LEVELFILE_EXTENSION     "lvl"
61 #define TAPEFILE_EXTENSION      "tap"
62 #define SCOREFILE_EXTENSION     "sco"
63 #define ERROR_FILENAME          "error.out"
64 #endif
65
66 /* file permissions for newly written files */
67 #define MODE_R_ALL              (S_IRUSR | S_IRGRP | S_IROTH)
68 #define MODE_W_ALL              (S_IWUSR | S_IWGRP | S_IWOTH)
69 #define MODE_X_ALL              (S_IXUSR | S_IXGRP | S_IXOTH)
70 #define USERDATA_DIR_MODE       (MODE_R_ALL | MODE_X_ALL | S_IWUSR)
71 #define LEVEL_PERMS             (MODE_R_ALL | MODE_W_ALL)
72 #define SCORE_PERMS             LEVEL_PERMS
73 #define TAPE_PERMS              LEVEL_PERMS
74 #define SETUP_PERMS             LEVEL_PERMS
75
76 /* sort priorities of level series (also used as level series classes) */
77 #define LEVELCLASS_TUTORIAL_START       10
78 #define LEVELCLASS_TUTORIAL_END         99
79 #define LEVELCLASS_CLASSICS_START       100
80 #define LEVELCLASS_CLASSICS_END         199
81 #define LEVELCLASS_CONTRIBUTION_START   200
82 #define LEVELCLASS_CONTRIBUTION_END     299
83 #define LEVELCLASS_USER_START           300
84 #define LEVELCLASS_USER_END             399
85 #define LEVELCLASS_UNDEFINED            999
86
87 static void SaveUserLevelInfo();                /* for 'InitUserLevelDir()' */
88 static char *getSetupLine(char *, int);         /* for 'SaveUserLevelInfo()' */
89
90 static char *getGlobalDataDir()
91 {
92   return GAME_DIR;
93 }
94
95 char *getUserDataDir()
96 {
97   static char *userdata_dir = NULL;
98
99   if (!userdata_dir)
100   {
101     char *home_dir = getHomeDir();
102     char *data_dir = USERDATA_DIRECTORY;
103
104     userdata_dir = getPath2(home_dir, data_dir);
105   }
106
107   return userdata_dir;
108 }
109
110 static char *getSetupDir()
111 {
112   return getUserDataDir();
113 }
114
115 static char *getUserLevelDir(char *level_subdir)
116 {
117   static char *userlevel_dir = NULL;
118   char *data_dir = getUserDataDir();
119   char *userlevel_subdir = LEVELS_DIRECTORY;
120
121   if (userlevel_dir)
122     free(userlevel_dir);
123
124   if (strlen(level_subdir) > 0)
125     userlevel_dir = getPath3(data_dir, userlevel_subdir, level_subdir);
126   else
127     userlevel_dir = getPath2(data_dir, userlevel_subdir);
128
129   return userlevel_dir;
130 }
131
132 static char *getTapeDir(char *level_subdir)
133 {
134   static char *tape_dir = NULL;
135   char *data_dir = getUserDataDir();
136   char *tape_subdir = TAPES_DIRECTORY;
137
138   if (tape_dir)
139     free(tape_dir);
140
141   if (strlen(level_subdir) > 0)
142     tape_dir = getPath3(data_dir, tape_subdir, level_subdir);
143   else
144     tape_dir = getPath2(data_dir, tape_subdir);
145
146   return tape_dir;
147 }
148
149 static char *getScoreDir(char *level_subdir)
150 {
151   static char *score_dir = NULL;
152   char *data_dir = getGlobalDataDir();
153   char *score_subdir = SCORES_DIRECTORY;
154
155   if (score_dir)
156     free(score_dir);
157
158   if (strlen(level_subdir) > 0)
159     score_dir = getPath3(data_dir, score_subdir, level_subdir);
160   else
161     score_dir = getPath2(data_dir, score_subdir);
162
163   return score_dir;
164 }
165
166 static char *getLevelFilename(int nr)
167 {
168   static char *filename = NULL;
169   char basename[MAX_FILENAME_LEN];
170
171   if (filename != NULL)
172     free(filename);
173
174   sprintf(basename, "%03d.%s", nr, LEVELFILE_EXTENSION);
175   filename = getPath3((leveldir[leveldir_nr].user_defined ?
176                        getUserLevelDir("") :
177                        options.level_directory),
178                       leveldir[leveldir_nr].filename,
179                       basename);
180
181   return filename;
182 }
183
184 static char *getTapeFilename(int nr)
185 {
186   static char *filename = NULL;
187   char basename[MAX_FILENAME_LEN];
188
189   if (filename != NULL)
190     free(filename);
191
192   sprintf(basename, "%03d.%s", nr, TAPEFILE_EXTENSION);
193   filename = getPath2(getTapeDir(leveldir[leveldir_nr].filename), basename);
194
195   return filename;
196 }
197
198 static char *getScoreFilename(int nr)
199 {
200   static char *filename = NULL;
201   char basename[MAX_FILENAME_LEN];
202
203   if (filename != NULL)
204     free(filename);
205
206   sprintf(basename, "%03d.%s", nr, SCOREFILE_EXTENSION);
207   filename = getPath2(getScoreDir(leveldir[leveldir_nr].filename), basename);
208
209   return filename;
210 }
211
212 static void createDirectory(char *dir, char *text)
213 {
214   if (access(dir, F_OK) != 0)
215     if (mkdir(dir, USERDATA_DIR_MODE) != 0)
216       Error(ERR_WARN, "cannot create %s directory '%s'", text, dir);
217 }
218
219 static void InitUserDataDirectory()
220 {
221   createDirectory(getUserDataDir(), "user data");
222 }
223
224 static void InitTapeDirectory(char *level_subdir)
225 {
226   createDirectory(getUserDataDir(), "user data");
227   createDirectory(getTapeDir(""), "main tape");
228   createDirectory(getTapeDir(level_subdir), "level tape");
229 }
230
231 static void InitScoreDirectory(char *level_subdir)
232 {
233   createDirectory(getScoreDir(""), "main score");
234   createDirectory(getScoreDir(level_subdir), "level score");
235 }
236
237 static void InitUserLevelDirectory(char *level_subdir)
238 {
239   if (access(getUserLevelDir(level_subdir), F_OK) != 0)
240   {
241     createDirectory(getUserDataDir(), "user data");
242     createDirectory(getUserLevelDir(""), "main user level");
243     createDirectory(getUserLevelDir(level_subdir), "user level");
244
245     SaveUserLevelInfo();
246   }
247 }
248
249 static void setLevelInfoToDefaults()
250 {
251   int i, x, y;
252
253   lev_fieldx = level.fieldx = STD_LEV_FIELDX;
254   lev_fieldy = level.fieldy = STD_LEV_FIELDY;
255
256   for(x=0; x<MAX_LEV_FIELDX; x++) 
257     for(y=0; y<MAX_LEV_FIELDY; y++) 
258       Feld[x][y] = Ur[x][y] = EL_ERDREICH;
259
260   level.time = 100;
261   level.edelsteine = 0;
262   level.tempo_amoebe = 10;
263   level.dauer_sieb = 10;
264   level.dauer_ablenk = 10;
265   level.amoebe_inhalt = EL_DIAMANT;
266
267   level.high_speed = FALSE;
268
269   strcpy(level.name, "Nameless Level");
270
271   for(i=0; i<LEVEL_SCORE_ELEMENTS; i++)
272     level.score[i] = 10;
273
274   MampferMax = 4;
275   for(i=0; i<8; i++)
276     for(x=0; x<3; x++)
277       for(y=0; y<3; y++)
278         level.mampfer_inhalt[i][x][y] = EL_FELSBROCKEN;
279
280   Feld[0][0] = Ur[0][0] = EL_SPIELFIGUR;
281   Feld[STD_LEV_FIELDX-1][STD_LEV_FIELDY-1] =
282     Ur[STD_LEV_FIELDX-1][STD_LEV_FIELDY-1] = EL_AUSGANG_ZU;
283 }
284
285 void LoadLevel(int level_nr)
286 {
287   int i, x, y;
288   char *filename = getLevelFilename(level_nr);
289   char cookie[MAX_LINE_LEN];
290   char chunk[CHUNK_ID_LEN + 1];
291   int file_version = FILE_VERSION_1_2;  /* last version of level files */
292   int chunk_length;
293   FILE *file;
294
295   /* always start with reliable default values */
296   setLevelInfoToDefaults();
297
298   if (!(file = fopen(filename, "r")))
299   {
300     Error(ERR_WARN, "cannot read level '%s' - creating new level", filename);
301     return;
302   }
303
304   /* check file identifier */
305   fgets(cookie, MAX_LINE_LEN, file);
306   if (strlen(cookie) > 0 && cookie[strlen(cookie) - 1] == '\n')
307     cookie[strlen(cookie) - 1] = '\0';
308
309   if (strcmp(cookie, LEVEL_COOKIE_10) == 0)     /* old 1.0 level format */
310     file_version = FILE_VERSION_1_0;
311   else if (strcmp(cookie, LEVEL_COOKIE) != 0)   /* unknown level format */
312   {
313     Error(ERR_WARN, "wrong file identifier of level file '%s'", filename);
314     fclose(file);
315     return;
316   }
317
318   /* read chunk "HEAD" */
319   if (file_version >= FILE_VERSION_1_2)
320   {
321     /* first check header chunk identifier and chunk length */
322     fgets(chunk, CHUNK_ID_LEN + 1, file);
323     chunk_length =
324       (fgetc(file)<<24) | (fgetc(file)<<16) | (fgetc(file)<<8) | fgetc(file);
325     if (strcmp(chunk, "HEAD") || chunk_length != LEVEL_HEADER_SIZE)
326     {
327       Error(ERR_WARN, "wrong 'HEAD' chunk of level file '%s'", filename);
328       fclose(file);
329       return;
330     }
331   }
332
333   lev_fieldx = level.fieldx = fgetc(file);
334   lev_fieldy = level.fieldy = fgetc(file);
335
336   level.time            = (fgetc(file)<<8) | fgetc(file);
337   level.edelsteine      = (fgetc(file)<<8) | fgetc(file);
338
339   for(i=0; i<MAX_LEVNAMLEN; i++)
340     level.name[i]       = fgetc(file);
341   level.name[MAX_LEVNAMLEN - 1] = 0;
342
343   for(i=0; i<LEVEL_SCORE_ELEMENTS; i++)
344     level.score[i]      = fgetc(file);
345
346   MampferMax = 4;
347   for(i=0; i<8; i++)
348   {
349     for(y=0; y<3; y++)
350     {
351       for(x=0; x<3; x++)
352       {
353         if (i < 4)
354           level.mampfer_inhalt[i][x][y] = fgetc(file);
355         else
356           level.mampfer_inhalt[i][x][y] = EL_LEERRAUM;
357       }
358     }
359   }
360
361   level.tempo_amoebe    = fgetc(file);
362   level.dauer_sieb      = fgetc(file);
363   level.dauer_ablenk    = fgetc(file);
364   level.amoebe_inhalt = fgetc(file);
365
366   for(i=0; i<LEVEL_HEADER_UNUSED; i++)  /* skip unused header bytes */
367     fgetc(file);
368
369   /* read chunk "BODY" */
370   if (file_version >= FILE_VERSION_1_2)
371   {
372     fgets(chunk, CHUNK_ID_LEN + 1, file);
373     chunk_length =
374       (fgetc(file)<<24) | (fgetc(file)<<16) | (fgetc(file)<<8) | fgetc(file);
375
376     /* look for optional content chunk */
377     if (strcmp(chunk, "CONT") == 0 && chunk_length == 4 + 8 * 3 * 3)
378     {
379       fgetc(file);
380       MampferMax = fgetc(file);
381       fgetc(file);
382       fgetc(file);
383
384       for(i=0; i<8; i++)
385         for(y=0; y<3; y++)
386           for(x=0; x<3; x++)
387             level.mampfer_inhalt[i][x][y] = fgetc(file);
388
389       fgets(chunk, CHUNK_ID_LEN + 1, file);
390       chunk_length =
391         (fgetc(file)<<24) | (fgetc(file)<<16) | (fgetc(file)<<8) | fgetc(file);
392     }
393
394     /* next check body chunk identifier and chunk length */
395     if (strcmp(chunk, "BODY") || chunk_length != lev_fieldx * lev_fieldy)
396     {
397       Error(ERR_WARN, "wrong 'BODY' chunk of level file '%s'", filename);
398       fclose(file);
399       return;
400     }
401   }
402
403   for(y=0; y<lev_fieldy; y++) 
404     for(x=0; x<lev_fieldx; x++) 
405       Feld[x][y] = Ur[x][y] = fgetc(file);
406
407   fclose(file);
408
409 #if 0
410   if (level.time <= 10)         /* minimum playing time of each level */
411     level.time = 10;
412 #endif
413
414   if (file_version == FILE_VERSION_1_0 &&
415       leveldir[leveldir_nr].sort_priority >= LEVELCLASS_CONTRIBUTION_START &&
416       leveldir[leveldir_nr].sort_priority <= LEVELCLASS_CONTRIBUTION_END)
417   {
418     Error(ERR_WARN, "level file '%s' has version number 1.0", filename);
419     Error(ERR_WARN, "using high speed movement for player");
420     level.high_speed = TRUE;
421   }
422 }
423
424 void SaveLevel(int level_nr)
425 {
426   int i, x, y;
427   char *filename = getLevelFilename(level_nr);
428   FILE *file;
429   int chunk_length;
430
431   if (!(file = fopen(filename, "w")))
432   {
433     Error(ERR_WARN, "cannot save level file '%s'", filename);
434     return;
435   }
436
437   fputs(LEVEL_COOKIE, file);            /* file identifier */
438   fputc('\n', file);
439
440   fputs("HEAD", file);                  /* chunk identifier for file header */
441
442   chunk_length = LEVEL_HEADER_SIZE;
443
444   fputc((chunk_length >>  24) & 0xff, file);
445   fputc((chunk_length >>  16) & 0xff, file);
446   fputc((chunk_length >>   8) & 0xff, file);
447   fputc((chunk_length >>   0) & 0xff, file);
448
449   fputc(level.fieldx, file);
450   fputc(level.fieldy, file);
451   fputc(level.time / 256, file);
452   fputc(level.time % 256, file);
453   fputc(level.edelsteine / 256, file);
454   fputc(level.edelsteine % 256, file);
455
456   for(i=0; i<MAX_LEVNAMLEN; i++)
457     fputc(level.name[i], file);
458   for(i=0; i<LEVEL_SCORE_ELEMENTS; i++)
459     fputc(level.score[i], file);
460   for(i=0; i<4; i++)
461     for(y=0; y<3; y++)
462       for(x=0; x<3; x++)
463         fputc(level.mampfer_inhalt[i][x][y], file);
464   fputc(level.tempo_amoebe, file);
465   fputc(level.dauer_sieb, file);
466   fputc(level.dauer_ablenk, file);
467   fputc(level.amoebe_inhalt, file);
468
469   for(i=0; i<LEVEL_HEADER_UNUSED; i++)  /* set unused header bytes to zero */
470     fputc(0, file);
471
472   fputs("CONT", file);                  /* chunk identifier for contents */
473
474   chunk_length = 4 + 8 * 3 * 3;
475
476   fputc((chunk_length >>  24) & 0xff, file);
477   fputc((chunk_length >>  16) & 0xff, file);
478   fputc((chunk_length >>   8) & 0xff, file);
479   fputc((chunk_length >>   0) & 0xff, file);
480
481   fputc(EL_MAMPFER, file);
482   fputc(MampferMax, file);
483   fputc(0, file);
484   fputc(0, file);
485
486   for(i=0; i<8; i++)
487     for(y=0; y<3; y++)
488       for(x=0; x<3; x++)
489         fputc(level.mampfer_inhalt[i][x][y], file);
490
491   fputs("BODY", file);                  /* chunk identifier for file body */
492   chunk_length = lev_fieldx * lev_fieldy;
493
494   fputc((chunk_length >>  24) & 0xff, file);
495   fputc((chunk_length >>  16) & 0xff, file);
496   fputc((chunk_length >>   8) & 0xff, file);
497   fputc((chunk_length >>   0) & 0xff, file);
498
499   for(y=0; y<lev_fieldy; y++) 
500     for(x=0; x<lev_fieldx; x++) 
501       fputc(Ur[x][y], file);
502
503   fclose(file);
504
505   chmod(filename, LEVEL_PERMS);
506 }
507
508 void LoadTape(int level_nr)
509 {
510   int i, j;
511   char *filename = getTapeFilename(level_nr);
512   char cookie[MAX_LINE_LEN];
513   char chunk[CHUNK_ID_LEN + 1];
514   FILE *file;
515   int num_participating_players;
516   int file_version = FILE_VERSION_1_2;  /* last version of tape files */
517   int chunk_length;
518
519   /* always start with reliable default values (empty tape) */
520   TapeErase();
521
522   /* default values (also for pre-1.2 tapes) with only the first player */
523   tape.player_participates[0] = TRUE;
524   for(i=1; i<MAX_PLAYERS; i++)
525     tape.player_participates[i] = FALSE;
526
527   /* at least one (default: the first) player participates in every tape */
528   num_participating_players = 1;
529
530   if (!(file = fopen(filename, "r")))
531     return;
532
533   /* check file identifier */
534   fgets(cookie, MAX_LINE_LEN, file);
535   if (strlen(cookie) > 0 && cookie[strlen(cookie) - 1] == '\n')
536     cookie[strlen(cookie) - 1] = '\0';
537
538   if (strcmp(cookie, TAPE_COOKIE_10) == 0)      /* old 1.0 tape format */
539     file_version = FILE_VERSION_1_0;
540   else if (strcmp(cookie, TAPE_COOKIE) != 0)    /* unknown tape format */
541   {
542     Error(ERR_WARN, "wrong file identifier of tape file '%s'", filename);
543     fclose(file);
544     return;
545   }
546
547   /* read chunk "HEAD" */
548   if (file_version >= FILE_VERSION_1_2)
549   {
550     /* first check header chunk identifier and chunk length */
551     fgets(chunk, CHUNK_ID_LEN + 1, file);
552     chunk_length =
553       (fgetc(file)<<24) | (fgetc(file)<<16) | (fgetc(file)<<8) | fgetc(file);
554
555     if (strcmp(chunk, "HEAD") || chunk_length != TAPE_HEADER_SIZE)
556     {
557       Error(ERR_WARN, "wrong 'HEAD' chunk of tape file '%s'", filename);
558       fclose(file);
559       return;
560     }
561   }
562
563   tape.random_seed =
564     (fgetc(file)<<24) | (fgetc(file)<<16) | (fgetc(file)<<8) | fgetc(file);
565   tape.date =
566     (fgetc(file)<<24) | (fgetc(file)<<16) | (fgetc(file)<<8) | fgetc(file);
567   tape.length =
568     (fgetc(file)<<24) | (fgetc(file)<<16) | (fgetc(file)<<8) | fgetc(file);
569
570   /* read header fields that are new since version 1.2 */
571   if (file_version >= FILE_VERSION_1_2)
572   {
573     byte store_participating_players = fgetc(file);
574
575     for(i=0; i<TAPE_HEADER_UNUSED; i++)         /* skip unused header bytes */
576       fgetc(file);
577
578     /* since version 1.2, tapes store which players participate in the tape */
579     num_participating_players = 0;
580     for(i=0; i<MAX_PLAYERS; i++)
581     {
582       tape.player_participates[i] = FALSE;
583
584       if (store_participating_players & (1 << i))
585       {
586         tape.player_participates[i] = TRUE;
587         num_participating_players++;
588       }
589     }
590   }
591
592   tape.level_nr = level_nr;
593   tape.counter = 0;
594   tape.changed = FALSE;
595
596   tape.recording = FALSE;
597   tape.playing = FALSE;
598   tape.pausing = FALSE;
599
600   /* read chunk "BODY" */
601   if (file_version >= FILE_VERSION_1_2)
602   {
603     /* next check body chunk identifier and chunk length */
604     fgets(chunk, CHUNK_ID_LEN + 1, file);
605     chunk_length =
606       (fgetc(file)<<24) | (fgetc(file)<<16) | (fgetc(file)<<8) | fgetc(file);
607     if (strcmp(chunk, "BODY") ||
608         chunk_length != (num_participating_players + 1) * tape.length)
609     {
610       Error(ERR_WARN, "wrong 'BODY' chunk of tape file '%s'", filename);
611       fclose(file);
612       return;
613     }
614   }
615
616   for(i=0; i<tape.length; i++)
617   {
618     if (i >= MAX_TAPELEN)
619       break;
620
621     for(j=0; j<MAX_PLAYERS; j++)
622     {
623       tape.pos[i].action[j] = MV_NO_MOVING;
624
625       if (tape.player_participates[j])
626         tape.pos[i].action[j] = fgetc(file);
627     }
628
629     tape.pos[i].delay = fgetc(file);
630
631     if (file_version == FILE_VERSION_1_0)
632     {
633       /* eliminate possible diagonal moves in old tapes */
634       /* this is only for backward compatibility */
635
636       byte joy_dir[4] = { JOY_LEFT, JOY_RIGHT, JOY_UP, JOY_DOWN };
637       byte action = tape.pos[i].action[0];
638       int k, num_moves = 0;
639
640       for (k=0; k<4; k++)
641       {
642         if (action & joy_dir[k])
643         {
644           tape.pos[i + num_moves].action[0] = joy_dir[k];
645           if (num_moves > 0)
646             tape.pos[i + num_moves].delay = 0;
647           num_moves++;
648         }
649       }
650
651       if (num_moves > 1)
652       {
653         num_moves--;
654         i += num_moves;
655         tape.length += num_moves;
656       }
657     }
658
659     if (feof(file))
660       break;
661   }
662
663   fclose(file);
664
665   if (i != tape.length)
666     Error(ERR_WARN, "level recording file '%s' corrupted", filename);
667
668   tape.length_seconds = GetTapeLength();
669 }
670
671 void SaveTape(int level_nr)
672 {
673   int i;
674   char *filename = getTapeFilename(level_nr);
675   FILE *file;
676   boolean new_tape = TRUE;
677   byte store_participating_players;
678   int num_participating_players;
679   int chunk_length;
680
681   InitTapeDirectory(leveldir[leveldir_nr].filename);
682
683   /* if a tape still exists, ask to overwrite it */
684   if (access(filename, F_OK) == 0)
685   {
686     new_tape = FALSE;
687     if (!Request("Replace old tape ?", REQ_ASK))
688       return;
689   }
690
691   /* count number of players and set corresponding bits for compact storage */
692   store_participating_players = 0;
693   num_participating_players = 0;
694   for(i=0; i<MAX_PLAYERS; i++)
695   {
696     if (tape.player_participates[i])
697     {
698       num_participating_players++;
699       store_participating_players |= (1 << i);
700     }
701   }
702
703   if (!(file = fopen(filename, "w")))
704   {
705     Error(ERR_WARN, "cannot save level recording file '%s'", filename);
706     return;
707   }
708
709   fputs(TAPE_COOKIE, file);             /* file identifier */
710   fputc('\n', file);
711
712   fputs("HEAD", file);                  /* chunk identifier for file header */
713
714   chunk_length = TAPE_HEADER_SIZE;
715
716   fputc((chunk_length >>  24) & 0xff, file);
717   fputc((chunk_length >>  16) & 0xff, file);
718   fputc((chunk_length >>   8) & 0xff, file);
719   fputc((chunk_length >>   0) & 0xff, file);
720
721   fputc((tape.random_seed >> 24) & 0xff, file);
722   fputc((tape.random_seed >> 16) & 0xff, file);
723   fputc((tape.random_seed >>  8) & 0xff, file);
724   fputc((tape.random_seed >>  0) & 0xff, file);
725
726   fputc((tape.date >>  24) & 0xff, file);
727   fputc((tape.date >>  16) & 0xff, file);
728   fputc((tape.date >>   8) & 0xff, file);
729   fputc((tape.date >>   0) & 0xff, file);
730
731   fputc((tape.length >>  24) & 0xff, file);
732   fputc((tape.length >>  16) & 0xff, file);
733   fputc((tape.length >>   8) & 0xff, file);
734   fputc((tape.length >>   0) & 0xff, file);
735
736   fputc(store_participating_players, file);
737
738   for(i=0; i<TAPE_HEADER_UNUSED; i++)   /* set unused header bytes to zero */
739     fputc(0, file);
740
741   fputs("BODY", file);                  /* chunk identifier for file body */
742   chunk_length = (num_participating_players + 1) * tape.length;
743
744   fputc((chunk_length >>  24) & 0xff, file);
745   fputc((chunk_length >>  16) & 0xff, file);
746   fputc((chunk_length >>   8) & 0xff, file);
747   fputc((chunk_length >>   0) & 0xff, file);
748
749   for(i=0; i<tape.length; i++)
750   {
751     int j;
752
753     for(j=0; j<MAX_PLAYERS; j++)
754       if (tape.player_participates[j])
755         fputc(tape.pos[i].action[j], file);
756
757     fputc(tape.pos[i].delay, file);
758   }
759
760   fclose(file);
761
762   chmod(filename, TAPE_PERMS);
763
764   tape.changed = FALSE;
765
766   if (new_tape)
767     Request("tape saved !", REQ_CONFIRM);
768 }
769
770 void LoadScore(int level_nr)
771 {
772   int i;
773   char *filename = getScoreFilename(level_nr);
774   char cookie[MAX_LINE_LEN];
775   char line[MAX_LINE_LEN];
776   char *line_ptr;
777   FILE *file;
778
779   /* always start with reliable default values */
780   for(i=0; i<MAX_SCORE_ENTRIES; i++)
781   {
782     strcpy(highscore[i].Name, EMPTY_PLAYER_NAME);
783     highscore[i].Score = 0;
784   }
785
786   if (!(file = fopen(filename, "r")))
787     return;
788
789   /* check file identifier */
790   fgets(cookie, MAX_LINE_LEN, file);
791   if (strlen(cookie) > 0 && cookie[strlen(cookie) - 1] == '\n')
792     cookie[strlen(cookie) - 1] = '\0';
793
794   if (strcmp(cookie, SCORE_COOKIE) != 0)
795   {
796     Error(ERR_WARN, "wrong file identifier of score file '%s'", filename);
797     fclose(file);
798     return;
799   }
800
801   for(i=0; i<MAX_SCORE_ENTRIES; i++)
802   {
803     fscanf(file, "%d", &highscore[i].Score);
804     fgets(line, MAX_LINE_LEN, file);
805
806     if (line[strlen(line)-1] == '\n')
807       line[strlen(line)-1] = '\0';
808
809     for (line_ptr = line; *line_ptr; line_ptr++)
810     {
811       if (*line_ptr != ' ' && *line_ptr != '\t' && *line_ptr != '\0')
812       {
813         strncpy(highscore[i].Name, line_ptr, MAX_NAMELEN - 1);
814         highscore[i].Name[MAX_NAMELEN - 1] = '\0';
815         break;
816       }
817     }
818   }
819
820   fclose(file);
821 }
822
823 void SaveScore(int level_nr)
824 {
825   int i;
826   char *filename = getScoreFilename(level_nr);
827   FILE *file;
828
829   InitScoreDirectory(leveldir[leveldir_nr].filename);
830
831   if (!(file = fopen(filename, "w")))
832   {
833     Error(ERR_WARN, "cannot save score for level %d", level_nr);
834     return;
835   }
836
837   fprintf(file, "%s\n\n", SCORE_COOKIE);
838
839   for(i=0; i<MAX_SCORE_ENTRIES; i++)
840     fprintf(file, "%d %s\n", highscore[i].Score, highscore[i].Name);
841
842   fclose(file);
843
844   chmod(filename, SCORE_PERMS);
845 }
846
847 #define TOKEN_STR_FILE_IDENTIFIER       "file_identifier"
848 #define TOKEN_STR_LAST_LEVEL_SERIES     "last_level_series"
849 #define TOKEN_STR_PLAYER_PREFIX         "player_"
850
851 #define TOKEN_VALUE_POSITION            30
852
853 /* global setup */
854 #define SETUP_TOKEN_PLAYER_NAME         0
855 #define SETUP_TOKEN_SOUND               1
856 #define SETUP_TOKEN_SOUND_LOOPS         2
857 #define SETUP_TOKEN_SOUND_MUSIC         3
858 #define SETUP_TOKEN_SOUND_SIMPLE        4
859 #define SETUP_TOKEN_TOONS               5
860 #define SETUP_TOKEN_DOUBLE_BUFFERING    6
861 #define SETUP_TOKEN_SCROLL_DELAY        7
862 #define SETUP_TOKEN_SOFT_SCROLLING      8
863 #define SETUP_TOKEN_FADING              9
864 #define SETUP_TOKEN_AUTORECORD          10
865 #define SETUP_TOKEN_QUICK_DOORS         11
866 #define SETUP_TOKEN_TEAM_MODE           12
867
868 /* player setup */
869 #define SETUP_TOKEN_USE_JOYSTICK        13
870 #define SETUP_TOKEN_JOY_DEVICE_NAME     14
871 #define SETUP_TOKEN_JOY_XLEFT           15
872 #define SETUP_TOKEN_JOY_XMIDDLE         16
873 #define SETUP_TOKEN_JOY_XRIGHT          17
874 #define SETUP_TOKEN_JOY_YUPPER          18
875 #define SETUP_TOKEN_JOY_YMIDDLE         19
876 #define SETUP_TOKEN_JOY_YLOWER          20
877 #define SETUP_TOKEN_JOY_SNAP            21
878 #define SETUP_TOKEN_JOY_BOMB            22
879 #define SETUP_TOKEN_KEY_LEFT            23
880 #define SETUP_TOKEN_KEY_RIGHT           24
881 #define SETUP_TOKEN_KEY_UP              25
882 #define SETUP_TOKEN_KEY_DOWN            26
883 #define SETUP_TOKEN_KEY_SNAP            27
884 #define SETUP_TOKEN_KEY_BOMB            28
885
886 /* level directory info */
887 #define LEVELINFO_TOKEN_NAME            29
888 #define LEVELINFO_TOKEN_LEVELS          30
889 #define LEVELINFO_TOKEN_FIRST_LEVEL     31
890 #define LEVELINFO_TOKEN_SORT_PRIORITY   32
891 #define LEVELINFO_TOKEN_READONLY        33
892
893 #define FIRST_GLOBAL_SETUP_TOKEN        SETUP_TOKEN_PLAYER_NAME
894 #define LAST_GLOBAL_SETUP_TOKEN         SETUP_TOKEN_TEAM_MODE
895
896 #define FIRST_PLAYER_SETUP_TOKEN        SETUP_TOKEN_USE_JOYSTICK
897 #define LAST_PLAYER_SETUP_TOKEN         SETUP_TOKEN_KEY_BOMB
898
899 #define FIRST_LEVELINFO_TOKEN           LEVELINFO_TOKEN_NAME
900 #define LAST_LEVELINFO_TOKEN            LEVELINFO_TOKEN_READONLY
901
902 #define TYPE_BOOLEAN                    1
903 #define TYPE_SWITCH                     2
904 #define TYPE_KEYSYM                     3
905 #define TYPE_INTEGER                    4
906 #define TYPE_STRING                     5
907
908 static struct SetupInfo si;
909 static struct SetupInputInfo sii;
910 static struct LevelDirInfo ldi;
911 static struct
912 {
913   int type;
914   void *value;
915   char *text;
916 } token_info[] =
917 {
918   /* global setup */
919   { TYPE_STRING,  &si.player_name,      "player_name"                   },
920   { TYPE_SWITCH,  &si.sound,            "sound"                         },
921   { TYPE_SWITCH,  &si.sound_loops,      "repeating_sound_loops"         },
922   { TYPE_SWITCH,  &si.sound_music,      "background_music"              },
923   { TYPE_SWITCH,  &si.sound_simple,     "simple_sound_effects"          },
924   { TYPE_SWITCH,  &si.toons,            "toons"                         },
925   { TYPE_SWITCH,  &si.double_buffering, "double_buffering"              },
926   { TYPE_SWITCH,  &si.scroll_delay,     "scroll_delay"                  },
927   { TYPE_SWITCH,  &si.soft_scrolling,   "soft_scrolling"                },
928   { TYPE_SWITCH,  &si.fading,           "screen_fading"                 },
929   { TYPE_SWITCH,  &si.autorecord,       "automatic_tape_recording"      },
930   { TYPE_SWITCH,  &si.quick_doors,      "quick_doors"                   },
931   { TYPE_SWITCH,  &si.team_mode,        "team_mode"                     },
932
933   /* player setup */
934   { TYPE_BOOLEAN, &sii.use_joystick,    ".use_joystick"                 },
935   { TYPE_STRING,  &sii.joy.device_name, ".joy.device_name"              },
936   { TYPE_INTEGER, &sii.joy.xleft,       ".joy.xleft"                    },
937   { TYPE_INTEGER, &sii.joy.xmiddle,     ".joy.xmiddle"                  },
938   { TYPE_INTEGER, &sii.joy.xright,      ".joy.xright"                   },
939   { TYPE_INTEGER, &sii.joy.yupper,      ".joy.yupper"                   },
940   { TYPE_INTEGER, &sii.joy.ymiddle,     ".joy.ymiddle"                  },
941   { TYPE_INTEGER, &sii.joy.ylower,      ".joy.ylower"                   },
942   { TYPE_INTEGER, &sii.joy.snap,        ".joy.snap_field"               },
943   { TYPE_INTEGER, &sii.joy.bomb,        ".joy.place_bomb"               },
944   { TYPE_KEYSYM,  &sii.key.left,        ".key.move_left"                },
945   { TYPE_KEYSYM,  &sii.key.right,       ".key.move_right"               },
946   { TYPE_KEYSYM,  &sii.key.up,          ".key.move_up"                  },
947   { TYPE_KEYSYM,  &sii.key.down,        ".key.move_down"                },
948   { TYPE_KEYSYM,  &sii.key.snap,        ".key.snap_field"               },
949   { TYPE_KEYSYM,  &sii.key.bomb,        ".key.place_bomb"               },
950
951   /* level directory info */
952   { TYPE_STRING,  &ldi.name,            "name"                          },
953   { TYPE_INTEGER, &ldi.levels,          "levels"                        },
954   { TYPE_INTEGER, &ldi.first_level,     "first_level"                   },
955   { TYPE_INTEGER, &ldi.sort_priority,   "sort_priority"                 },
956   { TYPE_BOOLEAN, &ldi.readonly,        "readonly"                      }
957 };
958
959 static char *string_tolower(char *s)
960 {
961   static char s_lower[100];
962   int i;
963
964   if (strlen(s) >= 100)
965     return s;
966
967   strcpy(s_lower, s);
968
969   for (i=0; i<strlen(s_lower); i++)
970     s_lower[i] = tolower(s_lower[i]);
971
972   return s_lower;
973 }
974
975 static int get_string_integer_value(char *s)
976 {
977   static char *number_text[][3] =
978   {
979     { "0", "zero", "null", },
980     { "1", "one", "first" },
981     { "2", "two", "second" },
982     { "3", "three", "third" },
983     { "4", "four", "fourth" },
984     { "5", "five", "fifth" },
985     { "6", "six", "sixth" },
986     { "7", "seven", "seventh" },
987     { "8", "eight", "eighth" },
988     { "9", "nine", "ninth" },
989     { "10", "ten", "tenth" },
990     { "11", "eleven", "eleventh" },
991     { "12", "twelve", "twelfth" },
992   };
993
994   int i, j;
995
996   for (i=0; i<13; i++)
997     for (j=0; j<3; j++)
998       if (strcmp(string_tolower(s), number_text[i][j]) == 0)
999         return i;
1000
1001   return atoi(s);
1002 }
1003
1004 static boolean get_string_boolean_value(char *s)
1005 {
1006   if (strcmp(string_tolower(s), "true") == 0 ||
1007       strcmp(string_tolower(s), "yes") == 0 ||
1008       strcmp(string_tolower(s), "on") == 0 ||
1009       get_string_integer_value(s) == 1)
1010     return TRUE;
1011   else
1012     return FALSE;
1013 }
1014
1015 static char *getFormattedSetupEntry(char *token, char *value)
1016 {
1017   int i;
1018   static char entry[MAX_LINE_LEN];
1019
1020   sprintf(entry, "%s:", token);
1021   for (i=strlen(entry); i<TOKEN_VALUE_POSITION; i++)
1022     entry[i] = ' ';
1023   entry[i] = '\0';
1024
1025   strcat(entry, value);
1026
1027   return entry;
1028 }
1029
1030 static void freeSetupFileList(struct SetupFileList *setup_file_list)
1031 {
1032   if (!setup_file_list)
1033     return;
1034
1035   if (setup_file_list->token)
1036     free(setup_file_list->token);
1037   if (setup_file_list->value)
1038     free(setup_file_list->value);
1039   if (setup_file_list->next)
1040     freeSetupFileList(setup_file_list->next);
1041   free(setup_file_list);
1042 }
1043
1044 static struct SetupFileList *newSetupFileList(char *token, char *value)
1045 {
1046   struct SetupFileList *new = checked_malloc(sizeof(struct SetupFileList));
1047
1048   new->token = checked_malloc(strlen(token) + 1);
1049   strcpy(new->token, token);
1050
1051   new->value = checked_malloc(strlen(value) + 1);
1052   strcpy(new->value, value);
1053
1054   new->next = NULL;
1055
1056   return new;
1057 }
1058
1059 static char *getTokenValue(struct SetupFileList *setup_file_list,
1060                            char *token)
1061 {
1062   if (!setup_file_list)
1063     return NULL;
1064
1065   if (strcmp(setup_file_list->token, token) == 0)
1066     return setup_file_list->value;
1067   else
1068     return getTokenValue(setup_file_list->next, token);
1069 }
1070
1071 static void setTokenValue(struct SetupFileList *setup_file_list,
1072                           char *token, char *value)
1073 {
1074   if (!setup_file_list)
1075     return;
1076
1077   if (strcmp(setup_file_list->token, token) == 0)
1078   {
1079     free(setup_file_list->value);
1080     setup_file_list->value = checked_malloc(strlen(value) + 1);
1081     strcpy(setup_file_list->value, value);
1082   }
1083   else if (setup_file_list->next == NULL)
1084     setup_file_list->next = newSetupFileList(token, value);
1085   else
1086     setTokenValue(setup_file_list->next, token, value);
1087 }
1088
1089 #ifdef DEBUG
1090 static void printSetupFileList(struct SetupFileList *setup_file_list)
1091 {
1092   if (!setup_file_list)
1093     return;
1094
1095   printf("token: '%s'\n", setup_file_list->token);
1096   printf("value: '%s'\n", setup_file_list->value);
1097
1098   printSetupFileList(setup_file_list->next);
1099 }
1100 #endif
1101
1102 static struct SetupFileList *loadSetupFileList(char *filename)
1103 {
1104   int line_len;
1105   char line[MAX_LINE_LEN];
1106   char *token, *value, *line_ptr;
1107   struct SetupFileList *setup_file_list = newSetupFileList("", "");
1108   struct SetupFileList *first_valid_list_entry;
1109
1110   FILE *file;
1111
1112   if (!(file = fopen(filename, "r")))
1113   {
1114     Error(ERR_WARN, "cannot open configuration file '%s'", filename);
1115     return NULL;
1116   }
1117
1118   while(!feof(file))
1119   {
1120     /* read next line of input file */
1121     if (!fgets(line, MAX_LINE_LEN, file))
1122       break;
1123
1124     /* cut trailing comment or whitespace from input line */
1125     for (line_ptr = line; *line_ptr; line_ptr++)
1126     {
1127       if (*line_ptr == '#' || *line_ptr == '\n')
1128       {
1129         *line_ptr = '\0';
1130         break;
1131       }
1132     }
1133
1134     /* cut trailing whitespaces from input line */
1135     for (line_ptr = &line[strlen(line)]; line_ptr > line; line_ptr--)
1136       if ((*line_ptr == ' ' || *line_ptr == '\t') && line_ptr[1] == '\0')
1137         *line_ptr = '\0';
1138
1139     /* ignore empty lines */
1140     if (*line == '\0')
1141       continue;
1142
1143     line_len = strlen(line);
1144
1145     /* cut leading whitespaces from token */
1146     for (token = line; *token; token++)
1147       if (*token != ' ' && *token != '\t')
1148         break;
1149
1150     /* find end of token */
1151     for (line_ptr = token; *line_ptr; line_ptr++)
1152     {
1153       if (*line_ptr == ' ' || *line_ptr == '\t' || *line_ptr == ':')
1154       {
1155         *line_ptr = '\0';
1156         break;
1157       }
1158     }
1159
1160     if (line_ptr < line + line_len)
1161       value = line_ptr + 1;
1162     else
1163       value = "\0";
1164
1165     /* cut leading whitespaces from value */
1166     for (; *value; value++)
1167       if (*value != ' ' && *value != '\t')
1168         break;
1169
1170     if (*token && *value)
1171       setTokenValue(setup_file_list, token, value);
1172   }
1173
1174   fclose(file);
1175
1176   first_valid_list_entry = setup_file_list->next;
1177
1178   /* free empty list header */
1179   setup_file_list->next = NULL;
1180   freeSetupFileList(setup_file_list);
1181
1182   if (first_valid_list_entry == NULL)
1183     Error(ERR_WARN, "configuration file '%s' is empty", filename);
1184
1185   return first_valid_list_entry;
1186 }
1187
1188 static void checkSetupFileListIdentifier(struct SetupFileList *setup_file_list,
1189                                          char *identifier)
1190 {
1191   if (!setup_file_list)
1192     return;
1193
1194   if (strcmp(setup_file_list->token, TOKEN_STR_FILE_IDENTIFIER) == 0)
1195   {
1196     if (strcmp(setup_file_list->value, identifier) != 0)
1197     {
1198       Error(ERR_WARN, "configuration file has wrong version");
1199       return;
1200     }
1201     else
1202       return;
1203   }
1204
1205   if (setup_file_list->next)
1206     checkSetupFileListIdentifier(setup_file_list->next, identifier);
1207   else
1208   {
1209     Error(ERR_WARN, "configuration file has no version information");
1210     return;
1211   }
1212 }
1213
1214 static void setLevelDirInfoToDefaults(struct LevelDirInfo *ldi)
1215 {
1216   ldi->name = getStringCopy("non-existing");
1217   ldi->levels = 0;
1218   ldi->first_level = 0;
1219   ldi->sort_priority = LEVELCLASS_UNDEFINED;    /* default: least priority */
1220   ldi->readonly = TRUE;
1221 }
1222
1223 static void setSetupInfoToDefaults(struct SetupInfo *si)
1224 {
1225   int i;
1226
1227   si->player_name = getStringCopy(getLoginName());
1228
1229   si->sound = TRUE;
1230   si->sound_loops = TRUE;
1231   si->sound_music = TRUE;
1232   si->sound_simple = TRUE;
1233   si->toons = TRUE;
1234   si->double_buffering = TRUE;
1235   si->direct_draw = !si->double_buffering;
1236   si->scroll_delay = TRUE;
1237   si->soft_scrolling = TRUE;
1238   si->fading = FALSE;
1239   si->autorecord = TRUE;
1240   si->quick_doors = FALSE;
1241
1242   for (i=0; i<MAX_PLAYERS; i++)
1243   {
1244     si->input[i].use_joystick = FALSE;
1245     si->input[i].joy.device_name = getStringCopy(joystick_device_name[i]);
1246     si->input[i].joy.xleft   = JOYSTICK_XLEFT;
1247     si->input[i].joy.xmiddle = JOYSTICK_XMIDDLE;
1248     si->input[i].joy.xright  = JOYSTICK_XRIGHT;
1249     si->input[i].joy.yupper  = JOYSTICK_YUPPER;
1250     si->input[i].joy.ymiddle = JOYSTICK_YMIDDLE;
1251     si->input[i].joy.ylower  = JOYSTICK_YLOWER;
1252     si->input[i].joy.snap  = (i == 0 ? JOY_BUTTON_1 : 0);
1253     si->input[i].joy.bomb  = (i == 0 ? JOY_BUTTON_2 : 0);
1254     si->input[i].key.left  = (i == 0 ? DEFAULT_KEY_LEFT  : KEY_UNDEFINDED);
1255     si->input[i].key.right = (i == 0 ? DEFAULT_KEY_RIGHT : KEY_UNDEFINDED);
1256     si->input[i].key.up    = (i == 0 ? DEFAULT_KEY_UP    : KEY_UNDEFINDED);
1257     si->input[i].key.down  = (i == 0 ? DEFAULT_KEY_DOWN  : KEY_UNDEFINDED);
1258     si->input[i].key.snap  = (i == 0 ? DEFAULT_KEY_SNAP  : KEY_UNDEFINDED);
1259     si->input[i].key.bomb  = (i == 0 ? DEFAULT_KEY_BOMB  : KEY_UNDEFINDED);
1260   }
1261 }
1262
1263 static void setSetupInfo(int token_nr, char *token_value)
1264 {
1265   int token_type = token_info[token_nr].type;
1266   void *setup_value = token_info[token_nr].value;
1267
1268   if (token_value == NULL)
1269     return;
1270
1271   /* set setup field to corresponding token value */
1272   switch (token_type)
1273   {
1274     case TYPE_BOOLEAN:
1275     case TYPE_SWITCH:
1276       *(boolean *)setup_value = get_string_boolean_value(token_value);
1277       break;
1278
1279     case TYPE_KEYSYM:
1280       *(KeySym *)setup_value = getKeySymFromX11KeyName(token_value);
1281       break;
1282
1283     case TYPE_INTEGER:
1284       *(int *)setup_value = get_string_integer_value(token_value);
1285       break;
1286
1287     case TYPE_STRING:
1288       if (*(char **)setup_value != NULL)
1289         free(*(char **)setup_value);
1290       *(char **)setup_value = getStringCopy(token_value);
1291       break;
1292
1293     default:
1294       break;
1295   }
1296 }
1297
1298 static void decodeSetupFileList(struct SetupFileList *setup_file_list)
1299 {
1300   int i, pnr;
1301
1302   if (!setup_file_list)
1303     return;
1304
1305   /* handle global setup values */
1306   si = setup;
1307   for (i=FIRST_GLOBAL_SETUP_TOKEN; i<=LAST_GLOBAL_SETUP_TOKEN; i++)
1308     setSetupInfo(i, getTokenValue(setup_file_list, token_info[i].text));
1309   setup = si;
1310
1311   /* handle player specific setup values */
1312   for (pnr=0; pnr<MAX_PLAYERS; pnr++)
1313   {
1314     char prefix[30];
1315
1316     sprintf(prefix, "%s%d", TOKEN_STR_PLAYER_PREFIX, pnr + 1);
1317
1318     sii = setup.input[pnr];
1319     for (i=FIRST_PLAYER_SETUP_TOKEN; i<=LAST_PLAYER_SETUP_TOKEN; i++)
1320     {
1321       char full_token[100];
1322
1323       sprintf(full_token, "%s%s", prefix, token_info[i].text);
1324       setSetupInfo(i, getTokenValue(setup_file_list, full_token));
1325     }
1326     setup.input[pnr] = sii;
1327   }
1328 }
1329
1330 int getLevelSeriesNrFromLevelSeriesName(char *level_series_name)
1331 {
1332   int i;
1333
1334   if (!level_series_name)
1335     return 0;
1336
1337   for (i=0; i<num_leveldirs; i++)
1338     if (strcmp(level_series_name, leveldir[i].filename) == 0)
1339       return i;
1340
1341   return 0;
1342 }
1343
1344 int getLastPlayedLevelOfLevelSeries(char *level_series_name)
1345 {
1346   char *token_value;
1347   int level_series_nr = getLevelSeriesNrFromLevelSeriesName(level_series_name);
1348   int last_level_nr = 0;
1349
1350   if (!level_series_name)
1351     return 0;
1352
1353   token_value = getTokenValue(level_setup_list, level_series_name);
1354
1355   if (token_value)
1356   {
1357     last_level_nr = atoi(token_value);
1358
1359     if (last_level_nr < leveldir[level_series_nr].first_level)
1360       last_level_nr = leveldir[level_series_nr].first_level;
1361     if (last_level_nr > leveldir[level_series_nr].last_level)
1362       last_level_nr = leveldir[level_series_nr].last_level;
1363   }
1364
1365   return last_level_nr;
1366 }
1367
1368 static int compareLevelDirInfoEntries(const void *object1, const void *object2)
1369 {
1370   const struct LevelDirInfo *entry1 = object1;
1371   const struct LevelDirInfo *entry2 = object2;
1372   int compare_result;
1373
1374   if (entry1->sort_priority != entry2->sort_priority)
1375     compare_result = entry1->sort_priority - entry2->sort_priority;
1376   else
1377   {
1378     char *name1 = getStringToLower(entry1->name);
1379     char *name2 = getStringToLower(entry2->name);
1380
1381     compare_result = strcmp(name1, name2);
1382
1383     free(name1);
1384     free(name2);
1385   }
1386
1387   return compare_result;
1388 }
1389
1390 static int LoadLevelInfoFromLevelDir(char *level_directory, int start_entry)
1391 {
1392   DIR *dir;
1393   struct stat file_status;
1394   char *directory = NULL;
1395   char *filename = NULL;
1396   struct SetupFileList *setup_file_list = NULL;
1397   struct dirent *dir_entry;
1398   int i, current_entry = start_entry;
1399
1400   if ((dir = opendir(level_directory)) == NULL)
1401   {
1402     Error(ERR_WARN, "cannot read level directory '%s'", level_directory);
1403     return current_entry;
1404   }
1405
1406   while (current_entry < MAX_LEVDIR_ENTRIES)
1407   {
1408     if ((dir_entry = readdir(dir)) == NULL)     /* last directory entry */
1409       break;
1410
1411     /* skip entries for current and parent directory */
1412     if (strcmp(dir_entry->d_name, ".")  == 0 ||
1413         strcmp(dir_entry->d_name, "..") == 0)
1414       continue;
1415
1416     /* find out if directory entry is itself a directory */
1417     directory = getPath2(level_directory, dir_entry->d_name);
1418     if (stat(directory, &file_status) != 0 ||           /* cannot stat file */
1419         (file_status.st_mode & S_IFMT) != S_IFDIR)      /* not a directory */
1420     {
1421       free(directory);
1422       continue;
1423     }
1424
1425     filename = getPath2(directory, LEVELINFO_FILENAME);
1426     setup_file_list = loadSetupFileList(filename);
1427
1428     if (setup_file_list)
1429     {
1430       checkSetupFileListIdentifier(setup_file_list, LEVELINFO_COOKIE);
1431       setLevelDirInfoToDefaults(&leveldir[current_entry]);
1432
1433       ldi = leveldir[current_entry];
1434       for (i=FIRST_LEVELINFO_TOKEN; i<=LAST_LEVELINFO_TOKEN; i++)
1435         setSetupInfo(i, getTokenValue(setup_file_list, token_info[i].text));
1436       leveldir[current_entry] = ldi;
1437
1438       leveldir[current_entry].filename = getStringCopy(dir_entry->d_name);
1439       leveldir[current_entry].last_level =
1440         leveldir[current_entry].first_level +
1441         leveldir[current_entry].levels - 1;
1442       leveldir[current_entry].user_defined =
1443         (level_directory == options.level_directory ? FALSE : TRUE);
1444
1445       freeSetupFileList(setup_file_list);
1446       current_entry++;
1447     }
1448     else
1449       Error(ERR_WARN, "ignoring level directory '%s'", directory);
1450
1451     free(directory);
1452     free(filename);
1453   }
1454
1455   if (current_entry == MAX_LEVDIR_ENTRIES)
1456     Error(ERR_WARN, "using %d level directories -- ignoring the rest",
1457           current_entry);
1458
1459   closedir(dir);
1460
1461   if (current_entry == start_entry)
1462     Error(ERR_WARN, "cannot find any valid level series in directory '%s'",
1463           level_directory);
1464
1465   return current_entry;
1466 }
1467
1468 void LoadLevelInfo()
1469 {
1470   InitUserLevelDirectory(getLoginName());
1471
1472   num_leveldirs = 0;
1473   leveldir_nr = 0;
1474
1475   num_leveldirs = LoadLevelInfoFromLevelDir(options.level_directory,
1476                                             num_leveldirs);
1477   num_leveldirs = LoadLevelInfoFromLevelDir(getUserLevelDir(""),
1478                                             num_leveldirs);
1479
1480   if (num_leveldirs == 0)
1481     Error(ERR_EXIT, "cannot find any valid level series in any directory");
1482
1483   if (num_leveldirs > 1)
1484     qsort(leveldir, num_leveldirs, sizeof(struct LevelDirInfo),
1485           compareLevelDirInfoEntries);
1486 }
1487
1488 static void SaveUserLevelInfo()
1489 {
1490   char *filename;
1491   FILE *file;
1492   int i;
1493
1494   filename = getPath2(getUserLevelDir(getLoginName()), LEVELINFO_FILENAME);
1495
1496   if (!(file = fopen(filename, "w")))
1497   {
1498     Error(ERR_WARN, "cannot write level info file '%s'", filename);
1499     free(filename);
1500     return;
1501   }
1502
1503   ldi.name = getLoginName();
1504   ldi.levels = 100;
1505   ldi.first_level = 0;
1506   ldi.sort_priority = LEVELCLASS_USER_START;
1507   ldi.readonly = FALSE;
1508
1509   fprintf(file, "%s\n\n",
1510           getFormattedSetupEntry(TOKEN_STR_FILE_IDENTIFIER, LEVELINFO_COOKIE));
1511
1512   for (i=FIRST_LEVELINFO_TOKEN; i<=LAST_LEVELINFO_TOKEN; i++)
1513     fprintf(file, "%s\n", getSetupLine("", i));
1514
1515   fclose(file);
1516   free(filename);
1517
1518   chmod(filename, SETUP_PERMS);
1519 }
1520
1521 void LoadSetup()
1522 {
1523   char *filename;
1524   struct SetupFileList *setup_file_list = NULL;
1525
1526   /* always start with reliable default values */
1527   setSetupInfoToDefaults(&setup);
1528
1529   filename = getPath2(getSetupDir(), SETUP_FILENAME);
1530
1531   setup_file_list = loadSetupFileList(filename);
1532
1533   if (setup_file_list)
1534   {
1535     checkSetupFileListIdentifier(setup_file_list, SETUP_COOKIE);
1536     decodeSetupFileList(setup_file_list);
1537
1538     setup.direct_draw = !setup.double_buffering;
1539
1540     freeSetupFileList(setup_file_list);
1541
1542     /* needed to work around problems with fixed length strings */
1543     if (strlen(setup.player_name) >= MAX_NAMELEN)
1544       setup.player_name[MAX_NAMELEN - 1] = '\0';
1545     else if (strlen(setup.player_name) < MAX_NAMELEN - 1)
1546     {
1547       char *new_name = checked_malloc(MAX_NAMELEN);
1548
1549       strcpy(new_name, setup.player_name);
1550       free(setup.player_name);
1551       setup.player_name = new_name;
1552     }
1553   }
1554   else
1555     Error(ERR_WARN, "using default setup values");
1556
1557   free(filename);
1558 }
1559
1560 static char *getSetupLine(char *prefix, int token_nr)
1561 {
1562   int i;
1563   static char entry[MAX_LINE_LEN];
1564   int token_type = token_info[token_nr].type;
1565   void *setup_value = token_info[token_nr].value;
1566   char *token_text = token_info[token_nr].text;
1567
1568   /* start with the prefix, token and some spaces to format output line */
1569   sprintf(entry, "%s%s:", prefix, token_text);
1570   for (i=strlen(entry); i<TOKEN_VALUE_POSITION; i++)
1571     strcat(entry, " ");
1572
1573   /* continue with the token's value (which can have different types) */
1574   switch (token_type)
1575   {
1576     case TYPE_BOOLEAN:
1577       strcat(entry, (*(boolean *)setup_value ? "true" : "false"));
1578       break;
1579
1580     case TYPE_SWITCH:
1581       strcat(entry, (*(boolean *)setup_value ? "on" : "off"));
1582       break;
1583
1584     case TYPE_KEYSYM:
1585       {
1586         KeySym keysym = *(KeySym *)setup_value;
1587         char *keyname = getKeyNameFromKeySym(keysym);
1588
1589         strcat(entry, getX11KeyNameFromKeySym(keysym));
1590         for (i=strlen(entry); i<50; i++)
1591           strcat(entry, " ");
1592
1593         /* add comment, if useful */
1594         if (strcmp(keyname, "(undefined)") != 0 &&
1595             strcmp(keyname, "(unknown)") != 0)
1596         {
1597           strcat(entry, "# ");
1598           strcat(entry, keyname);
1599         }
1600       }
1601       break;
1602
1603     case TYPE_INTEGER:
1604       {
1605         char buffer[MAX_LINE_LEN];
1606
1607         sprintf(buffer, "%d", *(int *)setup_value);
1608         strcat(entry, buffer);
1609       }
1610       break;
1611
1612     case TYPE_STRING:
1613       strcat(entry, *(char **)setup_value);
1614       break;
1615
1616     default:
1617       break;
1618   }
1619
1620   return entry;
1621 }
1622
1623 void SaveSetup()
1624 {
1625   int i, pnr;
1626   char *filename;
1627   FILE *file;
1628
1629   InitUserDataDirectory();
1630
1631   filename = getPath2(getSetupDir(), SETUP_FILENAME);
1632
1633   if (!(file = fopen(filename, "w")))
1634   {
1635     Error(ERR_WARN, "cannot write setup file '%s'", filename);
1636     free(filename);
1637     return;
1638   }
1639
1640   fprintf(file, "%s\n",
1641           getFormattedSetupEntry(TOKEN_STR_FILE_IDENTIFIER, SETUP_COOKIE));
1642   fprintf(file, "\n");
1643
1644   /* handle global setup values */
1645   si = setup;
1646   for (i=FIRST_GLOBAL_SETUP_TOKEN; i<=LAST_GLOBAL_SETUP_TOKEN; i++)
1647   {
1648     fprintf(file, "%s\n", getSetupLine("", i));
1649
1650     /* just to make things nicer :) */
1651     if (i == SETUP_TOKEN_PLAYER_NAME)
1652       fprintf(file, "\n");
1653   }
1654
1655   /* handle player specific setup values */
1656   for (pnr=0; pnr<MAX_PLAYERS; pnr++)
1657   {
1658     char prefix[30];
1659
1660     sprintf(prefix, "%s%d", TOKEN_STR_PLAYER_PREFIX, pnr + 1);
1661     fprintf(file, "\n");
1662
1663     sii = setup.input[pnr];
1664     for (i=FIRST_PLAYER_SETUP_TOKEN; i<=LAST_PLAYER_SETUP_TOKEN; i++)
1665       fprintf(file, "%s\n", getSetupLine(prefix, i));
1666   }
1667
1668   fclose(file);
1669   free(filename);
1670
1671   chmod(filename, SETUP_PERMS);
1672 }
1673
1674 void LoadLevelSetup()
1675 {
1676   char *filename;
1677
1678   /* always start with reliable default values */
1679   leveldir_nr = 0;
1680   level_nr = 0;
1681
1682   filename = getPath2(getSetupDir(), LEVELSETUP_FILENAME);
1683
1684   if (level_setup_list)
1685     freeSetupFileList(level_setup_list);
1686
1687   level_setup_list = loadSetupFileList(filename);
1688
1689   if (level_setup_list)
1690   {
1691     char *last_level_series =
1692       getTokenValue(level_setup_list, TOKEN_STR_LAST_LEVEL_SERIES);
1693
1694     leveldir_nr = getLevelSeriesNrFromLevelSeriesName(last_level_series);
1695     level_nr = getLastPlayedLevelOfLevelSeries(last_level_series);
1696
1697     checkSetupFileListIdentifier(level_setup_list, LEVELSETUP_COOKIE);
1698   }
1699   else
1700   {
1701     level_setup_list = newSetupFileList(TOKEN_STR_FILE_IDENTIFIER,
1702                                         LEVELSETUP_COOKIE);
1703     Error(ERR_WARN, "using default setup values");
1704   }
1705
1706   free(filename);
1707 }
1708
1709 void SaveLevelSetup()
1710 {
1711   char *filename;
1712   struct SetupFileList *list_entry = level_setup_list;
1713   FILE *file;
1714
1715   InitUserDataDirectory();
1716
1717   setTokenValue(level_setup_list,
1718                 TOKEN_STR_LAST_LEVEL_SERIES, leveldir[leveldir_nr].filename);
1719
1720   setTokenValue(level_setup_list,
1721                 leveldir[leveldir_nr].filename, int2str(level_nr, 0));
1722
1723   filename = getPath2(getSetupDir(), LEVELSETUP_FILENAME);
1724
1725   if (!(file = fopen(filename, "w")))
1726   {
1727     Error(ERR_WARN, "cannot write setup file '%s'", filename);
1728     free(filename);
1729     return;
1730   }
1731
1732   fprintf(file, "%s\n\n", getFormattedSetupEntry(TOKEN_STR_FILE_IDENTIFIER,
1733                                                  LEVELSETUP_COOKIE));
1734   while (list_entry)
1735   {
1736     if (strcmp(list_entry->token, TOKEN_STR_FILE_IDENTIFIER) != 0)
1737       fprintf(file, "%s\n",
1738               getFormattedSetupEntry(list_entry->token, list_entry->value));
1739
1740     /* just to make things nicer :) */
1741     if (strcmp(list_entry->token, TOKEN_STR_LAST_LEVEL_SERIES) == 0)
1742       fprintf(file, "\n");
1743
1744     list_entry = list_entry->next;
1745   }
1746
1747   fclose(file);
1748   free(filename);
1749
1750   chmod(filename, SETUP_PERMS);
1751 }
1752
1753 #ifdef MSDOS
1754 static boolean initErrorFile()
1755 {
1756   char *filename;
1757   FILE *error_file;
1758
1759   InitUserDataDirectory();
1760
1761   filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1762   error_file = fopen(filename, "w");
1763   free(filename);
1764
1765   if (error_file == NULL)
1766     return FALSE;
1767
1768   fclose(error_file);
1769
1770   return TRUE;
1771 }
1772
1773 FILE *openErrorFile()
1774 {
1775   static boolean first_access = TRUE;
1776   char *filename;
1777   FILE *error_file;
1778
1779   if (first_access)
1780   {
1781     if (!initErrorFile())
1782       return NULL;
1783
1784     first_access = FALSE;
1785   }
1786
1787   filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1788   error_file = fopen(filename, "a");
1789   free(filename);
1790
1791   return error_file;
1792 }
1793
1794 void dumpErrorFile()
1795 {
1796   char *filename;
1797   FILE *error_file;
1798
1799   filename = getPath2(getUserDataDir(), ERROR_FILENAME);
1800   error_file = fopen(filename, "r");
1801   free(filename);
1802
1803   if (error_file != NULL)
1804   {
1805     while (!feof(error_file))
1806       fputc(fgetc(error_file), stderr);
1807
1808     fclose(error_file);
1809   }
1810 }
1811 #endif