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