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