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