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