fixed compiler warning about uninitialized local variable
[rocksndiamonds.git] / src / files.c
1 // ============================================================================
2 // Rocks'n'Diamonds - McDuffin Strikes Back!
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
5 //                  Holger Schemel
6 //                  info@artsoft.org
7 //                  http://www.artsoft.org/
8 // ----------------------------------------------------------------------------
9 // files.c
10 // ============================================================================
11
12 #include <ctype.h>
13 #include <sys/stat.h>
14 #include <dirent.h>
15 #include <math.h>
16
17 #include "libgame/libgame.h"
18
19 #include "files.h"
20 #include "init.h"
21 #include "tools.h"
22 #include "tape.h"
23 #include "config.h"
24
25 #define ENABLE_UNUSED_CODE      0       /* currently unused functions */
26 #define ENABLE_HISTORIC_CHUNKS  0       /* only for historic reference */
27 #define ENABLE_RESERVED_CODE    0       /* reserved for later use */
28
29 #define CHUNK_ID_LEN            4       /* IFF style chunk id length  */
30 #define CHUNK_SIZE_UNDEFINED    0       /* undefined chunk size == 0  */
31 #define CHUNK_SIZE_NONE         -1      /* do not write chunk size    */
32
33 #define LEVEL_CHUNK_NAME_SIZE   MAX_LEVEL_NAME_LEN
34 #define LEVEL_CHUNK_AUTH_SIZE   MAX_LEVEL_AUTHOR_LEN
35
36 #define LEVEL_CHUNK_VERS_SIZE   8       /* size of file version chunk */
37 #define LEVEL_CHUNK_DATE_SIZE   4       /* size of file date chunk    */
38 #define LEVEL_CHUNK_HEAD_SIZE   80      /* size of level file header  */
39 #define LEVEL_CHUNK_HEAD_UNUSED 0       /* unused level header bytes  */
40 #define LEVEL_CHUNK_CNT2_SIZE   160     /* size of level CNT2 chunk   */
41 #define LEVEL_CHUNK_CNT2_UNUSED 11      /* unused CNT2 chunk bytes    */
42 #define LEVEL_CHUNK_CNT3_HEADER 16      /* size of level CNT3 header  */
43 #define LEVEL_CHUNK_CNT3_UNUSED 10      /* unused CNT3 chunk bytes    */
44 #define LEVEL_CPART_CUS3_SIZE   134     /* size of CUS3 chunk part    */
45 #define LEVEL_CPART_CUS3_UNUSED 15      /* unused CUS3 bytes / part   */
46 #define LEVEL_CHUNK_GRP1_SIZE   74      /* size of level GRP1 chunk   */
47
48 /* (element number, number of change pages, change page number) */
49 #define LEVEL_CHUNK_CUSX_UNCHANGED      (2 + (1 + 1) + (1 + 1))
50
51 /* (element number only) */
52 #define LEVEL_CHUNK_GRPX_UNCHANGED      2
53 #define LEVEL_CHUNK_NOTE_UNCHANGED      2
54
55 /* (nothing at all if unchanged) */
56 #define LEVEL_CHUNK_ELEM_UNCHANGED      0
57
58 #define TAPE_CHUNK_VERS_SIZE    8       /* size of file version chunk */
59 #define TAPE_CHUNK_HEAD_SIZE    20      /* size of tape file header   */
60 #define TAPE_CHUNK_HEAD_UNUSED  3       /* unused tape header bytes   */
61
62 #define LEVEL_CHUNK_CNT3_SIZE(x)         (LEVEL_CHUNK_CNT3_HEADER + (x))
63 #define LEVEL_CHUNK_CUS3_SIZE(x)         (2 + (x) * LEVEL_CPART_CUS3_SIZE)
64 #define LEVEL_CHUNK_CUS4_SIZE(x)         (96 + (x) * 48)
65
66 /* file identifier strings */
67 #define LEVEL_COOKIE_TMPL               "ROCKSNDIAMONDS_LEVEL_FILE_VERSION_x.x"
68 #define TAPE_COOKIE_TMPL                "ROCKSNDIAMONDS_TAPE_FILE_VERSION_x.x"
69 #define SCORE_COOKIE                    "ROCKSNDIAMONDS_SCORE_FILE_VERSION_1.2"
70
71 /* values for deciding when (not) to save configuration data */
72 #define SAVE_CONF_NEVER                 0
73 #define SAVE_CONF_ALWAYS                1
74 #define SAVE_CONF_WHEN_CHANGED          -1
75
76 /* values for chunks using micro chunks */
77 #define CONF_MASK_1_BYTE                0x00
78 #define CONF_MASK_2_BYTE                0x40
79 #define CONF_MASK_4_BYTE                0x80
80 #define CONF_MASK_MULTI_BYTES           0xc0
81
82 #define CONF_MASK_BYTES                 0xc0
83 #define CONF_MASK_TOKEN                 0x3f
84
85 #define CONF_VALUE_1_BYTE(x)            (CONF_MASK_1_BYTE       | (x))
86 #define CONF_VALUE_2_BYTE(x)            (CONF_MASK_2_BYTE       | (x))
87 #define CONF_VALUE_4_BYTE(x)            (CONF_MASK_4_BYTE       | (x))
88 #define CONF_VALUE_MULTI_BYTES(x)       (CONF_MASK_MULTI_BYTES  | (x))
89
90 /* these definitions are just for convenience of use and readability */
91 #define CONF_VALUE_8_BIT(x)             CONF_VALUE_1_BYTE(x)
92 #define CONF_VALUE_16_BIT(x)            CONF_VALUE_2_BYTE(x)
93 #define CONF_VALUE_32_BIT(x)            CONF_VALUE_4_BYTE(x)
94 #define CONF_VALUE_BYTES(x)             CONF_VALUE_MULTI_BYTES(x)
95
96 #define CONF_VALUE_NUM_BYTES(x)         ((x) == CONF_MASK_1_BYTE ? 1 :  \
97                                          (x) == CONF_MASK_2_BYTE ? 2 :  \
98                                          (x) == CONF_MASK_4_BYTE ? 4 : 0)
99
100 #define CONF_CONTENT_NUM_ELEMENTS       (3 * 3)
101 #define CONF_CONTENT_NUM_BYTES          (CONF_CONTENT_NUM_ELEMENTS * 2)
102 #define CONF_ELEMENT_NUM_BYTES          (2)
103
104 #define CONF_ENTITY_NUM_BYTES(t)        ((t) == TYPE_ELEMENT ||         \
105                                          (t) == TYPE_ELEMENT_LIST ?     \
106                                          CONF_ELEMENT_NUM_BYTES :       \
107                                          (t) == TYPE_CONTENT ||         \
108                                          (t) == TYPE_CONTENT_LIST ?     \
109                                          CONF_CONTENT_NUM_BYTES : 1)
110
111 #define CONF_ELEMENT_BYTE_POS(i)        ((i) * CONF_ELEMENT_NUM_BYTES)
112 #define CONF_ELEMENTS_ELEMENT(b,i)     ((b[CONF_ELEMENT_BYTE_POS(i)] << 8) |  \
113                                         (b[CONF_ELEMENT_BYTE_POS(i) + 1]))
114
115 #define CONF_CONTENT_ELEMENT_POS(c,x,y) ((c) * CONF_CONTENT_NUM_ELEMENTS +    \
116                                          (y) * 3 + (x))
117 #define CONF_CONTENT_BYTE_POS(c,x,y)    (CONF_CONTENT_ELEMENT_POS(c,x,y) *    \
118                                          CONF_ELEMENT_NUM_BYTES)
119 #define CONF_CONTENTS_ELEMENT(b,c,x,y) ((b[CONF_CONTENT_BYTE_POS(c,x,y)]<< 8)|\
120                                         (b[CONF_CONTENT_BYTE_POS(c,x,y) + 1]))
121
122 /* temporary variables used to store pointers to structure members */
123 static struct LevelInfo li;
124 static struct ElementInfo xx_ei, yy_ei;
125 static struct ElementChangeInfo xx_change;
126 static struct ElementGroupInfo xx_group;
127 static struct EnvelopeInfo xx_envelope;
128 static unsigned int xx_event_bits[NUM_CE_BITFIELDS];
129 static char xx_default_description[MAX_ELEMENT_NAME_LEN + 1];
130 static int xx_num_contents;
131 static int xx_current_change_page;
132 static char xx_default_string_empty[1] = "";
133 static int xx_string_length_unused;
134
135 struct LevelFileConfigInfo
136 {
137   int element;                  /* element for which data is to be stored */
138   int save_type;                /* save data always, never or when changed */
139   int data_type;                /* data type (used internally, not stored) */
140   int conf_type;                /* micro chunk identifier (stored in file) */
141
142   /* (mandatory) */
143   void *value;                  /* variable that holds the data to be stored */
144   int default_value;            /* initial default value for this variable */
145
146   /* (optional) */
147   void *value_copy;             /* variable that holds the data to be copied */
148   void *num_entities;           /* number of entities for multi-byte data */
149   int default_num_entities;     /* default number of entities for this data */
150   int max_num_entities;         /* maximal number of entities for this data */
151   char *default_string;         /* optional default string for string data */
152 };
153
154 static struct LevelFileConfigInfo chunk_config_INFO[] =
155 {
156   /* ---------- values not related to single elements ----------------------- */
157
158   {
159     -1,                                 SAVE_CONF_ALWAYS,
160     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
161     &li.game_engine_type,               GAME_ENGINE_TYPE_RND
162   },
163
164   {
165     -1,                                 SAVE_CONF_ALWAYS,
166     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
167     &li.fieldx,                         STD_LEV_FIELDX
168   },
169   {
170     -1,                                 SAVE_CONF_ALWAYS,
171     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
172     &li.fieldy,                         STD_LEV_FIELDY
173   },
174
175   {
176     -1,                                 SAVE_CONF_ALWAYS,
177     TYPE_INTEGER,                       CONF_VALUE_16_BIT(3),
178     &li.time,                           100
179   },
180
181   {
182     -1,                                 SAVE_CONF_ALWAYS,
183     TYPE_INTEGER,                       CONF_VALUE_16_BIT(4),
184     &li.gems_needed,                    0
185   },
186
187   {
188     -1,                                 -1,
189     TYPE_INTEGER,                       CONF_VALUE_32_BIT(2),
190     &li.random_seed,                    0
191   },
192
193   {
194     -1,                                 -1,
195     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(2),
196     &li.use_step_counter,               FALSE
197   },
198
199   {
200     -1,                                 -1,
201     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(4),
202     &li.wind_direction_initial,         MV_NONE
203   },
204
205   {
206     -1,                                 -1,
207     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(5),
208     &li.em_slippery_gems,               FALSE
209   },
210
211   {
212     -1,                                 -1,
213     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(6),
214     &li.use_custom_template,            FALSE
215   },
216
217   {
218     -1,                                 -1,
219     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(1),
220     &li.can_move_into_acid_bits,        ~0      /* default: everything can */
221   },
222
223   {
224     -1,                                 -1,
225     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(7),
226     &li.dont_collide_with_bits,         ~0      /* default: always deadly */
227   },
228
229   {
230     -1,                                 -1,
231     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
232     &li.em_explodes_by_fire,            FALSE
233   },
234
235   {
236     -1,                                 -1,
237     TYPE_INTEGER,                       CONF_VALUE_16_BIT(5),
238     &li.score[SC_TIME_BONUS],           1
239   },
240
241   {
242     -1,                                 -1,
243     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
244     &li.auto_exit_sokoban,              FALSE
245   },
246
247   {
248     -1,                                 -1,
249     -1,                                 -1,
250     NULL,                               -1
251   }
252 };
253
254 static struct LevelFileConfigInfo chunk_config_ELEM[] =
255 {
256   /* (these values are the same for each player) */
257   {
258     EL_PLAYER_1,                        -1,
259     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
260     &li.block_last_field,               FALSE   /* default case for EM levels */
261   },
262   {
263     EL_PLAYER_1,                        -1,
264     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(2),
265     &li.sp_block_last_field,            TRUE    /* default case for SP levels */
266   },
267   {
268     EL_PLAYER_1,                        -1,
269     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(3),
270     &li.instant_relocation,             FALSE
271   },
272   {
273     EL_PLAYER_1,                        -1,
274     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(4),
275     &li.can_pass_to_walkable,           FALSE
276   },
277   {
278     EL_PLAYER_1,                        -1,
279     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(5),
280     &li.block_snap_field,               TRUE
281   },
282   {
283     EL_PLAYER_1,                        -1,
284     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(6),
285     &li.continuous_snapping,            TRUE
286   },
287   {
288     EL_PLAYER_1,                        -1,
289     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(12),
290     &li.shifted_relocation,             FALSE
291   },
292   {
293     EL_PLAYER_1,                        -1,
294     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(15),
295     &li.lazy_relocation,                FALSE
296   },
297
298   /* (these values are different for each player) */
299   {
300     EL_PLAYER_1,                        -1,
301     TYPE_INTEGER,                       CONF_VALUE_8_BIT(7),
302     &li.initial_player_stepsize[0],     STEPSIZE_NORMAL
303   },
304   {
305     EL_PLAYER_1,                        -1,
306     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
307     &li.initial_player_gravity[0],      FALSE
308   },
309   {
310     EL_PLAYER_1,                        -1,
311     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
312     &li.use_start_element[0],           FALSE
313   },
314   {
315     EL_PLAYER_1,                        -1,
316     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
317     &li.start_element[0],               EL_PLAYER_1
318   },
319   {
320     EL_PLAYER_1,                        -1,
321     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
322     &li.use_artwork_element[0],         FALSE
323   },
324   {
325     EL_PLAYER_1,                        -1,
326     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(2),
327     &li.artwork_element[0],             EL_PLAYER_1
328   },
329   {
330     EL_PLAYER_1,                        -1,
331     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
332     &li.use_explosion_element[0],       FALSE
333   },
334   {
335     EL_PLAYER_1,                        -1,
336     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(3),
337     &li.explosion_element[0],           EL_PLAYER_1
338   },
339   {
340     EL_PLAYER_1,                        -1,
341     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
342     &li.use_initial_inventory[0],       FALSE
343   },
344   {
345     EL_PLAYER_1,                        -1,
346     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(14),
347     &li.initial_inventory_size[0],      1
348   },
349   {
350     EL_PLAYER_1,                        -1,
351     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(1),
352     &li.initial_inventory_content[0][0],EL_EMPTY, NULL,
353     &li.initial_inventory_size[0],      1, MAX_INITIAL_INVENTORY_SIZE
354   },
355
356   {
357     EL_PLAYER_2,                        -1,
358     TYPE_INTEGER,                       CONF_VALUE_8_BIT(7),
359     &li.initial_player_stepsize[1],     STEPSIZE_NORMAL
360   },
361   {
362     EL_PLAYER_2,                        -1,
363     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
364     &li.initial_player_gravity[1],      FALSE
365   },
366   {
367     EL_PLAYER_2,                        -1,
368     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
369     &li.use_start_element[1],           FALSE
370   },
371   {
372     EL_PLAYER_2,                        -1,
373     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
374     &li.start_element[1],               EL_PLAYER_2
375   },
376   {
377     EL_PLAYER_2,                        -1,
378     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
379     &li.use_artwork_element[1],         FALSE
380   },
381   {
382     EL_PLAYER_2,                        -1,
383     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(2),
384     &li.artwork_element[1],             EL_PLAYER_2
385   },
386   {
387     EL_PLAYER_2,                        -1,
388     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
389     &li.use_explosion_element[1],       FALSE
390   },
391   {
392     EL_PLAYER_2,                        -1,
393     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(3),
394     &li.explosion_element[1],           EL_PLAYER_2
395   },
396   {
397     EL_PLAYER_2,                        -1,
398     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
399     &li.use_initial_inventory[1],       FALSE
400   },
401   {
402     EL_PLAYER_2,                        -1,
403     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(14),
404     &li.initial_inventory_size[1],      1
405   },
406   {
407     EL_PLAYER_2,                        -1,
408     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(1),
409     &li.initial_inventory_content[1][0],EL_EMPTY, NULL,
410     &li.initial_inventory_size[1],      1, MAX_INITIAL_INVENTORY_SIZE
411   },
412
413   {
414     EL_PLAYER_3,                        -1,
415     TYPE_INTEGER,                       CONF_VALUE_8_BIT(7),
416     &li.initial_player_stepsize[2],     STEPSIZE_NORMAL
417   },
418   {
419     EL_PLAYER_3,                        -1,
420     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
421     &li.initial_player_gravity[2],      FALSE
422   },
423   {
424     EL_PLAYER_3,                        -1,
425     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
426     &li.use_start_element[2],           FALSE
427   },
428   {
429     EL_PLAYER_3,                        -1,
430     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
431     &li.start_element[2],               EL_PLAYER_3
432   },
433   {
434     EL_PLAYER_3,                        -1,
435     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
436     &li.use_artwork_element[2],         FALSE
437   },
438   {
439     EL_PLAYER_3,                        -1,
440     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(2),
441     &li.artwork_element[2],             EL_PLAYER_3
442   },
443   {
444     EL_PLAYER_3,                        -1,
445     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
446     &li.use_explosion_element[2],       FALSE
447   },
448   {
449     EL_PLAYER_3,                        -1,
450     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(3),
451     &li.explosion_element[2],           EL_PLAYER_3
452   },
453   {
454     EL_PLAYER_3,                        -1,
455     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
456     &li.use_initial_inventory[2],       FALSE
457   },
458   {
459     EL_PLAYER_3,                        -1,
460     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(14),
461     &li.initial_inventory_size[2],      1
462   },
463   {
464     EL_PLAYER_3,                        -1,
465     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(1),
466     &li.initial_inventory_content[2][0],EL_EMPTY, NULL,
467     &li.initial_inventory_size[2],      1, MAX_INITIAL_INVENTORY_SIZE
468   },
469
470   {
471     EL_PLAYER_4,                        -1,
472     TYPE_INTEGER,                       CONF_VALUE_8_BIT(7),
473     &li.initial_player_stepsize[3],     STEPSIZE_NORMAL
474   },
475   {
476     EL_PLAYER_4,                        -1,
477     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
478     &li.initial_player_gravity[3],      FALSE
479   },
480   {
481     EL_PLAYER_4,                        -1,
482     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
483     &li.use_start_element[3],           FALSE
484   },
485   {
486     EL_PLAYER_4,                        -1,
487     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
488     &li.start_element[3],               EL_PLAYER_4
489   },
490   {
491     EL_PLAYER_4,                        -1,
492     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
493     &li.use_artwork_element[3],         FALSE
494   },
495   {
496     EL_PLAYER_4,                        -1,
497     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(2),
498     &li.artwork_element[3],             EL_PLAYER_4
499   },
500   {
501     EL_PLAYER_4,                        -1,
502     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
503     &li.use_explosion_element[3],       FALSE
504   },
505   {
506     EL_PLAYER_4,                        -1,
507     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(3),
508     &li.explosion_element[3],           EL_PLAYER_4
509   },
510   {
511     EL_PLAYER_4,                        -1,
512     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
513     &li.use_initial_inventory[3],       FALSE
514   },
515   {
516     EL_PLAYER_4,                        -1,
517     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(14),
518     &li.initial_inventory_size[3],      1
519   },
520   {
521     EL_PLAYER_4,                        -1,
522     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(1),
523     &li.initial_inventory_content[3][0],EL_EMPTY, NULL,
524     &li.initial_inventory_size[3],      1, MAX_INITIAL_INVENTORY_SIZE
525   },
526
527   {
528     EL_EMERALD,                         -1,
529     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
530     &li.score[SC_EMERALD],              10
531   },
532
533   {
534     EL_DIAMOND,                         -1,
535     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
536     &li.score[SC_DIAMOND],              10
537   },
538
539   {
540     EL_BUG,                             -1,
541     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
542     &li.score[SC_BUG],                  10
543   },
544
545   {
546     EL_SPACESHIP,                       -1,
547     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
548     &li.score[SC_SPACESHIP],            10
549   },
550
551   {
552     EL_PACMAN,                          -1,
553     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
554     &li.score[SC_PACMAN],               10
555   },
556
557   {
558     EL_NUT,                             -1,
559     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
560     &li.score[SC_NUT],                  10
561   },
562
563   {
564     EL_DYNAMITE,                        -1,
565     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
566     &li.score[SC_DYNAMITE],             10
567   },
568
569   {
570     EL_KEY_1,                           -1,
571     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
572     &li.score[SC_KEY],                  10
573   },
574
575   {
576     EL_PEARL,                           -1,
577     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
578     &li.score[SC_PEARL],                10
579   },
580
581   {
582     EL_CRYSTAL,                         -1,
583     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
584     &li.score[SC_CRYSTAL],              10
585   },
586
587   {
588     EL_BD_AMOEBA,                       -1,
589     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
590     &li.amoeba_content,                 EL_DIAMOND
591   },
592   {
593     EL_BD_AMOEBA,                       -1,
594     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
595     &li.amoeba_speed,                   10
596   },
597   {
598     EL_BD_AMOEBA,                       -1,
599     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
600     &li.grow_into_diggable,             TRUE
601   },
602
603   {
604     EL_YAMYAM,                          -1,
605     TYPE_CONTENT_LIST,                  CONF_VALUE_BYTES(1),
606     &li.yamyam_content,                 EL_ROCK, NULL,
607     &li.num_yamyam_contents,            4, MAX_ELEMENT_CONTENTS
608   },
609   {
610     EL_YAMYAM,                          -1,
611     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
612     &li.score[SC_YAMYAM],               10
613   },
614
615   {
616     EL_ROBOT,                           -1,
617     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
618     &li.score[SC_ROBOT],                10
619   },
620   {
621     EL_ROBOT,                           -1,
622     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
623     &li.slurp_score,                    10
624   },
625
626   {
627     EL_ROBOT_WHEEL,                     -1,
628     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
629     &li.time_wheel,                     10
630   },
631
632   {
633     EL_MAGIC_WALL,                      -1,
634     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
635     &li.time_magic_wall,                10
636   },
637
638   {
639     EL_GAME_OF_LIFE,                    -1,
640     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
641     &li.game_of_life[0],                2
642   },
643   {
644     EL_GAME_OF_LIFE,                    -1,
645     TYPE_INTEGER,                       CONF_VALUE_8_BIT(2),
646     &li.game_of_life[1],                3
647   },
648   {
649     EL_GAME_OF_LIFE,                    -1,
650     TYPE_INTEGER,                       CONF_VALUE_8_BIT(3),
651     &li.game_of_life[2],                3
652   },
653   {
654     EL_GAME_OF_LIFE,                    -1,
655     TYPE_INTEGER,                       CONF_VALUE_8_BIT(4),
656     &li.game_of_life[3],                3
657   },
658
659   {
660     EL_BIOMAZE,                         -1,
661     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
662     &li.biomaze[0],                     2
663   },
664   {
665     EL_BIOMAZE,                         -1,
666     TYPE_INTEGER,                       CONF_VALUE_8_BIT(2),
667     &li.biomaze[1],                     3
668   },
669   {
670     EL_BIOMAZE,                         -1,
671     TYPE_INTEGER,                       CONF_VALUE_8_BIT(3),
672     &li.biomaze[2],                     3
673   },
674   {
675     EL_BIOMAZE,                         -1,
676     TYPE_INTEGER,                       CONF_VALUE_8_BIT(4),
677     &li.biomaze[3],                     3
678   },
679
680   {
681     EL_TIMEGATE_SWITCH,                 -1,
682     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
683     &li.time_timegate,                  10
684   },
685
686   {
687     EL_LIGHT_SWITCH_ACTIVE,             -1,
688     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
689     &li.time_light,                     10
690   },
691
692   {
693     EL_SHIELD_NORMAL,                   -1,
694     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
695     &li.shield_normal_time,             10
696   },
697   {
698     EL_SHIELD_NORMAL,                   -1,
699     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
700     &li.score[SC_SHIELD],               10
701   },
702
703   {
704     EL_SHIELD_DEADLY,                   -1,
705     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
706     &li.shield_deadly_time,             10
707   },
708   {
709     EL_SHIELD_DEADLY,                   -1,
710     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
711     &li.score[SC_SHIELD],               10
712   },
713
714   {
715     EL_EXTRA_TIME,                      -1,
716     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
717     &li.extra_time,                     10
718   },
719   {
720     EL_EXTRA_TIME,                      -1,
721     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
722     &li.extra_time_score,               10
723   },
724
725   {
726     EL_TIME_ORB_FULL,                   -1,
727     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
728     &li.time_orb_time,                  10
729   },
730   {
731     EL_TIME_ORB_FULL,                   -1,
732     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
733     &li.use_time_orb_bug,               FALSE
734   },
735
736   {
737     EL_SPRING,                          -1,
738     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
739     &li.use_spring_bug,                 FALSE
740   },
741
742   {
743     EL_EMC_ANDROID,                     -1,
744     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
745     &li.android_move_time,              10
746   },
747   {
748     EL_EMC_ANDROID,                     -1,
749     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
750     &li.android_clone_time,             10
751   },
752   {
753     EL_EMC_ANDROID,                     -1,
754     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(1),
755     &li.android_clone_element[0],       EL_EMPTY, NULL,
756     &li.num_android_clone_elements,     1, MAX_ANDROID_ELEMENTS
757   },
758
759   {
760     EL_EMC_LENSES,                      -1,
761     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
762     &li.lenses_score,                   10
763   },
764   {
765     EL_EMC_LENSES,                      -1,
766     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
767     &li.lenses_time,                    10
768   },
769
770   {
771     EL_EMC_MAGNIFIER,                   -1,
772     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
773     &li.magnify_score,                  10
774   },
775   {
776     EL_EMC_MAGNIFIER,                   -1,
777     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
778     &li.magnify_time,                   10
779   },
780
781   {
782     EL_EMC_MAGIC_BALL,                  -1,
783     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
784     &li.ball_time,                      10
785   },
786   {
787     EL_EMC_MAGIC_BALL,                  -1,
788     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
789     &li.ball_random,                    FALSE
790   },
791   {
792     EL_EMC_MAGIC_BALL,                  -1,
793     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(2),
794     &li.ball_state_initial,             FALSE
795   },
796   {
797     EL_EMC_MAGIC_BALL,                  -1,
798     TYPE_CONTENT_LIST,                  CONF_VALUE_BYTES(1),
799     &li.ball_content,                   EL_EMPTY, NULL,
800     &li.num_ball_contents,              4, MAX_ELEMENT_CONTENTS
801   },
802
803   /* ---------- unused values ----------------------------------------------- */
804
805   {
806     EL_UNKNOWN,                         SAVE_CONF_NEVER,
807     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
808     &li.score[SC_UNKNOWN_14],           10
809   },
810   {
811     EL_UNKNOWN,                         SAVE_CONF_NEVER,
812     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
813     &li.score[SC_UNKNOWN_15],           10
814   },
815
816   {
817     -1,                                 -1,
818     -1,                                 -1,
819     NULL,                               -1
820   }
821 };
822
823 static struct LevelFileConfigInfo chunk_config_NOTE[] =
824 {
825   {
826     -1,                                 -1,
827     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
828     &xx_envelope.xsize,                 MAX_ENVELOPE_XSIZE,
829   },
830   {
831     -1,                                 -1,
832     TYPE_INTEGER,                       CONF_VALUE_8_BIT(2),
833     &xx_envelope.ysize,                 MAX_ENVELOPE_YSIZE,
834   },
835
836   {
837     -1,                                 -1,
838     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(3),
839     &xx_envelope.autowrap,              FALSE
840   },
841   {
842     -1,                                 -1,
843     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(4),
844     &xx_envelope.centered,              FALSE
845   },
846
847   {
848     -1,                                 -1,
849     TYPE_STRING,                        CONF_VALUE_BYTES(1),
850     &xx_envelope.text,                  -1, NULL,
851     &xx_string_length_unused,           -1, MAX_ENVELOPE_TEXT_LEN,
852     &xx_default_string_empty[0]
853   },
854
855   {
856     -1,                                 -1,
857     -1,                                 -1,
858     NULL,                               -1
859   }
860 };
861
862 static struct LevelFileConfigInfo chunk_config_CUSX_base[] =
863 {
864   {
865     -1,                                 -1,
866     TYPE_STRING,                        CONF_VALUE_BYTES(1),
867     &xx_ei.description[0],              -1,
868     &yy_ei.description[0],
869     &xx_string_length_unused,           -1, MAX_ELEMENT_NAME_LEN,
870     &xx_default_description[0]
871   },
872
873   {
874     -1,                                 -1,
875     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(1),
876     &xx_ei.properties[EP_BITFIELD_BASE_NR], EP_BITMASK_BASE_DEFAULT,
877     &yy_ei.properties[EP_BITFIELD_BASE_NR]
878   },
879 #if ENABLE_RESERVED_CODE
880   /* (reserved for later use) */
881   {
882     -1,                                 -1,
883     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(2),
884     &xx_ei.properties[EP_BITFIELD_BASE_NR + 1], EP_BITMASK_DEFAULT,
885     &yy_ei.properties[EP_BITFIELD_BASE_NR + 1]
886   },
887 #endif
888
889   {
890     -1,                                 -1,
891     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
892     &xx_ei.use_gfx_element,             FALSE,
893     &yy_ei.use_gfx_element
894   },
895   {
896     -1,                                 -1,
897     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
898     &xx_ei.gfx_element_initial,         EL_EMPTY_SPACE,
899     &yy_ei.gfx_element_initial
900   },
901
902   {
903     -1,                                 -1,
904     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(2),
905     &xx_ei.access_direction,            MV_ALL_DIRECTIONS,
906     &yy_ei.access_direction
907   },
908
909   {
910     -1,                                 -1,
911     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
912     &xx_ei.collect_score_initial,       10,
913     &yy_ei.collect_score_initial
914   },
915   {
916     -1,                                 -1,
917     TYPE_INTEGER,                       CONF_VALUE_16_BIT(3),
918     &xx_ei.collect_count_initial,       1,
919     &yy_ei.collect_count_initial
920   },
921
922   {
923     -1,                                 -1,
924     TYPE_INTEGER,                       CONF_VALUE_16_BIT(4),
925     &xx_ei.ce_value_fixed_initial,      0,
926     &yy_ei.ce_value_fixed_initial
927   },
928   {
929     -1,                                 -1,
930     TYPE_INTEGER,                       CONF_VALUE_16_BIT(5),
931     &xx_ei.ce_value_random_initial,     0,
932     &yy_ei.ce_value_random_initial
933   },
934   {
935     -1,                                 -1,
936     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(3),
937     &xx_ei.use_last_ce_value,           FALSE,
938     &yy_ei.use_last_ce_value
939   },
940
941   {
942     -1,                                 -1,
943     TYPE_INTEGER,                       CONF_VALUE_16_BIT(6),
944     &xx_ei.push_delay_fixed,            8,
945     &yy_ei.push_delay_fixed
946   },
947   {
948     -1,                                 -1,
949     TYPE_INTEGER,                       CONF_VALUE_16_BIT(7),
950     &xx_ei.push_delay_random,           8,
951     &yy_ei.push_delay_random
952   },
953   {
954     -1,                                 -1,
955     TYPE_INTEGER,                       CONF_VALUE_16_BIT(8),
956     &xx_ei.drop_delay_fixed,            0,
957     &yy_ei.drop_delay_fixed
958   },
959   {
960     -1,                                 -1,
961     TYPE_INTEGER,                       CONF_VALUE_16_BIT(9),
962     &xx_ei.drop_delay_random,           0,
963     &yy_ei.drop_delay_random
964   },
965   {
966     -1,                                 -1,
967     TYPE_INTEGER,                       CONF_VALUE_16_BIT(10),
968     &xx_ei.move_delay_fixed,            0,
969     &yy_ei.move_delay_fixed
970   },
971   {
972     -1,                                 -1,
973     TYPE_INTEGER,                       CONF_VALUE_16_BIT(11),
974     &xx_ei.move_delay_random,           0,
975     &yy_ei.move_delay_random
976   },
977
978   {
979     -1,                                 -1,
980     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(3),
981     &xx_ei.move_pattern,                MV_ALL_DIRECTIONS,
982     &yy_ei.move_pattern
983   },
984   {
985     -1,                                 -1,
986     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(4),
987     &xx_ei.move_direction_initial,      MV_START_AUTOMATIC,
988     &yy_ei.move_direction_initial
989   },
990   {
991     -1,                                 -1,
992     TYPE_INTEGER,                       CONF_VALUE_8_BIT(5),
993     &xx_ei.move_stepsize,               TILEX / 8,
994     &yy_ei.move_stepsize
995   },
996
997   {
998     -1,                                 -1,
999     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(12),
1000     &xx_ei.move_enter_element,          EL_EMPTY_SPACE,
1001     &yy_ei.move_enter_element
1002   },
1003   {
1004     -1,                                 -1,
1005     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(13),
1006     &xx_ei.move_leave_element,          EL_EMPTY_SPACE,
1007     &yy_ei.move_leave_element
1008   },
1009   {
1010     -1,                                 -1,
1011     TYPE_INTEGER,                       CONF_VALUE_8_BIT(6),
1012     &xx_ei.move_leave_type,             LEAVE_TYPE_UNLIMITED,
1013     &yy_ei.move_leave_type
1014   },
1015
1016   {
1017     -1,                                 -1,
1018     TYPE_INTEGER,                       CONF_VALUE_8_BIT(7),
1019     &xx_ei.slippery_type,               SLIPPERY_ANY_RANDOM,
1020     &yy_ei.slippery_type
1021   },
1022
1023   {
1024     -1,                                 -1,
1025     TYPE_INTEGER,                       CONF_VALUE_8_BIT(8),
1026     &xx_ei.explosion_type,              EXPLODES_3X3,
1027     &yy_ei.explosion_type
1028   },
1029   {
1030     -1,                                 -1,
1031     TYPE_INTEGER,                       CONF_VALUE_16_BIT(14),
1032     &xx_ei.explosion_delay,             16,
1033     &yy_ei.explosion_delay
1034   },
1035   {
1036     -1,                                 -1,
1037     TYPE_INTEGER,                       CONF_VALUE_16_BIT(15),
1038     &xx_ei.ignition_delay,              8,
1039     &yy_ei.ignition_delay
1040   },
1041
1042   {
1043     -1,                                 -1,
1044     TYPE_CONTENT_LIST,                  CONF_VALUE_BYTES(2),
1045     &xx_ei.content,                     EL_EMPTY_SPACE,
1046     &yy_ei.content,
1047     &xx_num_contents,                   1, 1
1048   },
1049
1050   /* ---------- "num_change_pages" must be the last entry ------------------- */
1051
1052   {
1053     -1,                                 SAVE_CONF_ALWAYS,
1054     TYPE_INTEGER,                       CONF_VALUE_8_BIT(9),
1055     &xx_ei.num_change_pages,            1,
1056     &yy_ei.num_change_pages
1057   },
1058
1059   {
1060     -1,                                 -1,
1061     -1,                                 -1,
1062     NULL,                               -1,
1063     NULL
1064   }
1065 };
1066
1067 static struct LevelFileConfigInfo chunk_config_CUSX_change[] =
1068 {
1069   /* ---------- "current_change_page" must be the first entry --------------- */
1070
1071   {
1072     -1,                                 SAVE_CONF_ALWAYS,
1073     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
1074     &xx_current_change_page,            -1
1075   },
1076
1077   /* ---------- (the remaining entries can be in any order) ----------------- */
1078
1079   {
1080     -1,                                 -1,
1081     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(2),
1082     &xx_change.can_change,              FALSE
1083   },
1084
1085   {
1086     -1,                                 -1,
1087     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(1),
1088     &xx_event_bits[0],                  0
1089   },
1090   {
1091     -1,                                 -1,
1092     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(2),
1093     &xx_event_bits[1],                  0
1094   },
1095
1096   {
1097     -1,                                 -1,
1098     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(3),
1099     &xx_change.trigger_player,          CH_PLAYER_ANY
1100   },
1101   {
1102     -1,                                 -1,
1103     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(4),
1104     &xx_change.trigger_side,            CH_SIDE_ANY
1105   },
1106   {
1107     -1,                                 -1,
1108     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(3),
1109     &xx_change.trigger_page,            CH_PAGE_ANY
1110   },
1111
1112   {
1113     -1,                                 -1,
1114     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
1115     &xx_change.target_element,          EL_EMPTY_SPACE
1116   },
1117
1118   {
1119     -1,                                 -1,
1120     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
1121     &xx_change.delay_fixed,             0
1122   },
1123   {
1124     -1,                                 -1,
1125     TYPE_INTEGER,                       CONF_VALUE_16_BIT(3),
1126     &xx_change.delay_random,            0
1127   },
1128   {
1129     -1,                                 -1,
1130     TYPE_INTEGER,                       CONF_VALUE_16_BIT(4),
1131     &xx_change.delay_frames,            FRAMES_PER_SECOND
1132   },
1133
1134   {
1135     -1,                                 -1,
1136     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(5),
1137     &xx_change.initial_trigger_element, EL_EMPTY_SPACE
1138   },
1139
1140   {
1141     -1,                                 -1,
1142     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(6),
1143     &xx_change.explode,                 FALSE
1144   },
1145   {
1146     -1,                                 -1,
1147     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(7),
1148     &xx_change.use_target_content,      FALSE
1149   },
1150   {
1151     -1,                                 -1,
1152     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
1153     &xx_change.only_if_complete,        FALSE
1154   },
1155   {
1156     -1,                                 -1,
1157     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
1158     &xx_change.use_random_replace,      FALSE
1159   },
1160   {
1161     -1,                                 -1,
1162     TYPE_INTEGER,                       CONF_VALUE_8_BIT(10),
1163     &xx_change.random_percentage,       100
1164   },
1165   {
1166     -1,                                 -1,
1167     TYPE_INTEGER,                       CONF_VALUE_8_BIT(11),
1168     &xx_change.replace_when,            CP_WHEN_EMPTY
1169   },
1170
1171   {
1172     -1,                                 -1,
1173     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(12),
1174     &xx_change.has_action,              FALSE
1175   },
1176   {
1177     -1,                                 -1,
1178     TYPE_INTEGER,                       CONF_VALUE_8_BIT(13),
1179     &xx_change.action_type,             CA_NO_ACTION
1180   },
1181   {
1182     -1,                                 -1,
1183     TYPE_INTEGER,                       CONF_VALUE_8_BIT(14),
1184     &xx_change.action_mode,             CA_MODE_UNDEFINED
1185   },
1186   {
1187     -1,                                 -1,
1188     TYPE_INTEGER,                       CONF_VALUE_16_BIT(6),
1189     &xx_change.action_arg,              CA_ARG_UNDEFINED
1190   },
1191
1192   {
1193     -1,                                 -1,
1194     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(7),
1195     &xx_change.action_element,          EL_EMPTY_SPACE
1196   },
1197
1198   {
1199     -1,                                 -1,
1200     TYPE_CONTENT_LIST,                  CONF_VALUE_BYTES(1),
1201     &xx_change.target_content,          EL_EMPTY_SPACE, NULL,
1202     &xx_num_contents,                   1, 1
1203   },
1204
1205   {
1206     -1,                                 -1,
1207     -1,                                 -1,
1208     NULL,                               -1
1209   }
1210 };
1211
1212 static struct LevelFileConfigInfo chunk_config_GRPX[] =
1213 {
1214   {
1215     -1,                                 -1,
1216     TYPE_STRING,                        CONF_VALUE_BYTES(1),
1217     &xx_ei.description[0],              -1, NULL,
1218     &xx_string_length_unused,           -1, MAX_ELEMENT_NAME_LEN,
1219     &xx_default_description[0]
1220   },
1221
1222   {
1223     -1,                                 -1,
1224     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
1225     &xx_ei.use_gfx_element,             FALSE
1226   },
1227   {
1228     -1,                                 -1,
1229     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
1230     &xx_ei.gfx_element_initial,         EL_EMPTY_SPACE
1231   },
1232
1233   {
1234     -1,                                 -1,
1235     TYPE_INTEGER,                       CONF_VALUE_8_BIT(2),
1236     &xx_group.choice_mode,              ANIM_RANDOM
1237   },
1238
1239   {
1240     -1,                                 -1,
1241     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(2),
1242     &xx_group.element[0],               EL_EMPTY_SPACE, NULL,
1243     &xx_group.num_elements,             1, MAX_ELEMENTS_IN_GROUP
1244   },
1245
1246   {
1247     -1,                                 -1,
1248     -1,                                 -1,
1249     NULL,                               -1
1250   }
1251 };
1252
1253 static struct LevelFileConfigInfo chunk_config_CONF[] =         /* (OBSOLETE) */
1254 {
1255   {
1256     EL_PLAYER_1,                        -1,
1257     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
1258     &li.block_snap_field,               TRUE
1259   },
1260   {
1261     EL_PLAYER_1,                        -1,
1262     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
1263     &li.continuous_snapping,            TRUE
1264   },
1265   {
1266     EL_PLAYER_1,                        -1,
1267     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
1268     &li.initial_player_stepsize[0],     STEPSIZE_NORMAL
1269   },
1270   {
1271     EL_PLAYER_1,                        -1,
1272     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
1273     &li.use_start_element[0],           FALSE
1274   },
1275   {
1276     EL_PLAYER_1,                        -1,
1277     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
1278     &li.start_element[0],               EL_PLAYER_1
1279   },
1280   {
1281     EL_PLAYER_1,                        -1,
1282     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
1283     &li.use_artwork_element[0],         FALSE
1284   },
1285   {
1286     EL_PLAYER_1,                        -1,
1287     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(2),
1288     &li.artwork_element[0],             EL_PLAYER_1
1289   },
1290   {
1291     EL_PLAYER_1,                        -1,
1292     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(12),
1293     &li.use_explosion_element[0],       FALSE
1294   },
1295   {
1296     EL_PLAYER_1,                        -1,
1297     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(3),
1298     &li.explosion_element[0],           EL_PLAYER_1
1299   },
1300
1301   {
1302     -1,                                 -1,
1303     -1,                                 -1,
1304     NULL,                               -1
1305   }
1306 };
1307
1308 static struct
1309 {
1310   int filetype;
1311   char *id;
1312 }
1313 filetype_id_list[] =
1314 {
1315   { LEVEL_FILE_TYPE_RND,        "RND"   },
1316   { LEVEL_FILE_TYPE_BD,         "BD"    },
1317   { LEVEL_FILE_TYPE_EM,         "EM"    },
1318   { LEVEL_FILE_TYPE_SP,         "SP"    },
1319   { LEVEL_FILE_TYPE_DX,         "DX"    },
1320   { LEVEL_FILE_TYPE_SB,         "SB"    },
1321   { LEVEL_FILE_TYPE_DC,         "DC"    },
1322   { -1,                         NULL    },
1323 };
1324
1325
1326 /* ========================================================================= */
1327 /* level file functions                                                      */
1328 /* ========================================================================= */
1329
1330 static boolean check_special_flags(char *flag)
1331 {
1332   if (strEqual(options.special_flags, flag) ||
1333       strEqual(leveldir_current->special_flags, flag))
1334     return TRUE;
1335
1336   return FALSE;
1337 }
1338
1339 static struct DateInfo getCurrentDate()
1340 {
1341   time_t epoch_seconds = time(NULL);
1342   struct tm *now = localtime(&epoch_seconds);
1343   struct DateInfo date;
1344
1345   date.year  = now->tm_year + 1900;
1346   date.month = now->tm_mon  + 1;
1347   date.day   = now->tm_mday;
1348
1349   date.src   = DATE_SRC_CLOCK;
1350
1351   return date;
1352 }
1353
1354 static void resetEventFlags(struct ElementChangeInfo *change)
1355 {
1356   int i;
1357
1358   for (i = 0; i < NUM_CHANGE_EVENTS; i++)
1359     change->has_event[i] = FALSE;
1360 }
1361
1362 static void resetEventBits()
1363 {
1364   int i;
1365
1366   for (i = 0; i < NUM_CE_BITFIELDS; i++)
1367     xx_event_bits[i] = 0;
1368 }
1369
1370 static void setEventFlagsFromEventBits(struct ElementChangeInfo *change)
1371 {
1372   int i;
1373
1374   /* important: only change event flag if corresponding event bit is set
1375      (this is because all xx_event_bits[] values are loaded separately,
1376      and all xx_event_bits[] values are set back to zero before loading
1377      another value xx_event_bits[x] (each value representing 32 flags)) */
1378
1379   for (i = 0; i < NUM_CHANGE_EVENTS; i++)
1380     if (xx_event_bits[CH_EVENT_BITFIELD_NR(i)] & CH_EVENT_BIT(i))
1381       change->has_event[i] = TRUE;
1382 }
1383
1384 static void setEventBitsFromEventFlags(struct ElementChangeInfo *change)
1385 {
1386   int i;
1387
1388   /* in contrast to the above function setEventFlagsFromEventBits(), it
1389      would also be possible to set all bits in xx_event_bits[] to 0 or 1
1390      depending on the corresponding change->has_event[i] values here, as
1391      all xx_event_bits[] values are reset in resetEventBits() before */
1392
1393   for (i = 0; i < NUM_CHANGE_EVENTS; i++)
1394     if (change->has_event[i])
1395       xx_event_bits[CH_EVENT_BITFIELD_NR(i)] |= CH_EVENT_BIT(i);
1396 }
1397
1398 static char *getDefaultElementDescription(struct ElementInfo *ei)
1399 {
1400   static char description[MAX_ELEMENT_NAME_LEN + 1];
1401   char *default_description = (ei->custom_description != NULL ?
1402                                ei->custom_description :
1403                                ei->editor_description);
1404   int i;
1405
1406   /* always start with reliable default values */
1407   for (i = 0; i < MAX_ELEMENT_NAME_LEN + 1; i++)
1408     description[i] = '\0';
1409
1410   /* truncate element description to MAX_ELEMENT_NAME_LEN bytes */
1411   strncpy(description, default_description, MAX_ELEMENT_NAME_LEN);
1412
1413   return &description[0];
1414 }
1415
1416 static void setElementDescriptionToDefault(struct ElementInfo *ei)
1417 {
1418   char *default_description = getDefaultElementDescription(ei);
1419   int i;
1420
1421   for (i = 0; i < MAX_ELEMENT_NAME_LEN + 1; i++)
1422     ei->description[i] = default_description[i];
1423 }
1424
1425 static void setConfigToDefaultsFromConfigList(struct LevelFileConfigInfo *conf)
1426 {
1427   int i;
1428
1429   for (i = 0; conf[i].data_type != -1; i++)
1430   {
1431     int default_value = conf[i].default_value;
1432     int data_type = conf[i].data_type;
1433     int conf_type = conf[i].conf_type;
1434     int byte_mask = conf_type & CONF_MASK_BYTES;
1435
1436     if (byte_mask == CONF_MASK_MULTI_BYTES)
1437     {
1438       int default_num_entities = conf[i].default_num_entities;
1439       int max_num_entities = conf[i].max_num_entities;
1440
1441       *(int *)(conf[i].num_entities) = default_num_entities;
1442
1443       if (data_type == TYPE_STRING)
1444       {
1445         char *default_string = conf[i].default_string;
1446         char *string = (char *)(conf[i].value);
1447
1448         strncpy(string, default_string, max_num_entities);
1449       }
1450       else if (data_type == TYPE_ELEMENT_LIST)
1451       {
1452         int *element_array = (int *)(conf[i].value);
1453         int j;
1454
1455         for (j = 0; j < max_num_entities; j++)
1456           element_array[j] = default_value;
1457       }
1458       else if (data_type == TYPE_CONTENT_LIST)
1459       {
1460         struct Content *content = (struct Content *)(conf[i].value);
1461         int c, x, y;
1462
1463         for (c = 0; c < max_num_entities; c++)
1464           for (y = 0; y < 3; y++)
1465             for (x = 0; x < 3; x++)
1466               content[c].e[x][y] = default_value;
1467       }
1468     }
1469     else        /* constant size configuration data (1, 2 or 4 bytes) */
1470     {
1471       if (data_type == TYPE_BOOLEAN)
1472         *(boolean *)(conf[i].value) = default_value;
1473       else
1474         *(int *)    (conf[i].value) = default_value;
1475     }
1476   }
1477 }
1478
1479 static void copyConfigFromConfigList(struct LevelFileConfigInfo *conf)
1480 {
1481   int i;
1482
1483   for (i = 0; conf[i].data_type != -1; i++)
1484   {
1485     int data_type = conf[i].data_type;
1486     int conf_type = conf[i].conf_type;
1487     int byte_mask = conf_type & CONF_MASK_BYTES;
1488
1489     if (byte_mask == CONF_MASK_MULTI_BYTES)
1490     {
1491       int max_num_entities = conf[i].max_num_entities;
1492
1493       if (data_type == TYPE_STRING)
1494       {
1495         char *string      = (char *)(conf[i].value);
1496         char *string_copy = (char *)(conf[i].value_copy);
1497
1498         strncpy(string_copy, string, max_num_entities);
1499       }
1500       else if (data_type == TYPE_ELEMENT_LIST)
1501       {
1502         int *element_array      = (int *)(conf[i].value);
1503         int *element_array_copy = (int *)(conf[i].value_copy);
1504         int j;
1505
1506         for (j = 0; j < max_num_entities; j++)
1507           element_array_copy[j] = element_array[j];
1508       }
1509       else if (data_type == TYPE_CONTENT_LIST)
1510       {
1511         struct Content *content      = (struct Content *)(conf[i].value);
1512         struct Content *content_copy = (struct Content *)(conf[i].value_copy);
1513         int c, x, y;
1514
1515         for (c = 0; c < max_num_entities; c++)
1516           for (y = 0; y < 3; y++)
1517             for (x = 0; x < 3; x++)
1518               content_copy[c].e[x][y] = content[c].e[x][y];
1519       }
1520     }
1521     else        /* constant size configuration data (1, 2 or 4 bytes) */
1522     {
1523       if (data_type == TYPE_BOOLEAN)
1524         *(boolean *)(conf[i].value_copy) = *(boolean *)(conf[i].value);
1525       else
1526         *(int *)    (conf[i].value_copy) = *(int *)    (conf[i].value);
1527     }
1528   }
1529 }
1530
1531 void copyElementInfo(struct ElementInfo *ei_from, struct ElementInfo *ei_to)
1532 {
1533   int i;
1534
1535   xx_ei = *ei_from;     /* copy element data into temporary buffer */
1536   yy_ei = *ei_to;       /* copy element data into temporary buffer */
1537
1538   copyConfigFromConfigList(chunk_config_CUSX_base);
1539
1540   *ei_from = xx_ei;
1541   *ei_to   = yy_ei;
1542
1543   /* ---------- reinitialize and copy change pages ---------- */
1544
1545   ei_to->num_change_pages = ei_from->num_change_pages;
1546   ei_to->current_change_page = ei_from->current_change_page;
1547
1548   setElementChangePages(ei_to, ei_to->num_change_pages);
1549
1550   for (i = 0; i < ei_to->num_change_pages; i++)
1551     ei_to->change_page[i] = ei_from->change_page[i];
1552
1553   /* ---------- copy group element info ---------- */
1554   if (ei_from->group != NULL && ei_to->group != NULL)   /* group or internal */
1555     *ei_to->group = *ei_from->group;
1556
1557   /* mark this custom element as modified */
1558   ei_to->modified_settings = TRUE;
1559 }
1560
1561 void setElementChangePages(struct ElementInfo *ei, int change_pages)
1562 {
1563   int change_page_size = sizeof(struct ElementChangeInfo);
1564
1565   ei->num_change_pages = MAX(1, change_pages);
1566
1567   ei->change_page =
1568     checked_realloc(ei->change_page, ei->num_change_pages * change_page_size);
1569
1570   if (ei->current_change_page >= ei->num_change_pages)
1571     ei->current_change_page = ei->num_change_pages - 1;
1572
1573   ei->change = &ei->change_page[ei->current_change_page];
1574 }
1575
1576 void setElementChangeInfoToDefaults(struct ElementChangeInfo *change)
1577 {
1578   xx_change = *change;          /* copy change data into temporary buffer */
1579
1580   setConfigToDefaultsFromConfigList(chunk_config_CUSX_change);
1581
1582   *change = xx_change;
1583
1584   resetEventFlags(change);
1585
1586   change->direct_action = 0;
1587   change->other_action = 0;
1588
1589   change->pre_change_function = NULL;
1590   change->change_function = NULL;
1591   change->post_change_function = NULL;
1592 }
1593
1594 static void setLevelInfoToDefaults_Level(struct LevelInfo *level)
1595 {
1596   int i, x, y;
1597
1598   li = *level;          /* copy level data into temporary buffer */
1599   setConfigToDefaultsFromConfigList(chunk_config_INFO);
1600   *level = li;          /* copy temporary buffer back to level data */
1601
1602   setLevelInfoToDefaults_EM();
1603   setLevelInfoToDefaults_SP();
1604
1605   level->native_em_level = &native_em_level;
1606   level->native_sp_level = &native_sp_level;
1607
1608   level->file_version = FILE_VERSION_ACTUAL;
1609   level->game_version = GAME_VERSION_ACTUAL;
1610
1611   level->creation_date = getCurrentDate();
1612
1613   level->encoding_16bit_field  = TRUE;
1614   level->encoding_16bit_yamyam = TRUE;
1615   level->encoding_16bit_amoeba = TRUE;
1616
1617   /* clear level name and level author string buffers */
1618   for (i = 0; i < MAX_LEVEL_NAME_LEN; i++)
1619     level->name[i] = '\0';
1620   for (i = 0; i < MAX_LEVEL_AUTHOR_LEN; i++)
1621     level->author[i] = '\0';
1622
1623   /* set level name and level author to default values */
1624   strcpy(level->name, NAMELESS_LEVEL_NAME);
1625   strcpy(level->author, ANONYMOUS_NAME);
1626
1627   /* set level playfield to playable default level with player and exit */
1628   for (x = 0; x < MAX_LEV_FIELDX; x++)
1629     for (y = 0; y < MAX_LEV_FIELDY; y++)
1630       level->field[x][y] = EL_SAND;
1631
1632   level->field[0][0] = EL_PLAYER_1;
1633   level->field[STD_LEV_FIELDX - 1][STD_LEV_FIELDY - 1] = EL_EXIT_CLOSED;
1634
1635   BorderElement = EL_STEELWALL;
1636
1637   /* set all bug compatibility flags to "false" => do not emulate this bug */
1638   level->use_action_after_change_bug = FALSE;
1639
1640   if (leveldir_current)
1641   {
1642     /* try to determine better author name than 'anonymous' */
1643     if (!strEqual(leveldir_current->author, ANONYMOUS_NAME))
1644     {
1645       strncpy(level->author, leveldir_current->author, MAX_LEVEL_AUTHOR_LEN);
1646       level->author[MAX_LEVEL_AUTHOR_LEN] = '\0';
1647     }
1648     else
1649     {
1650       switch (LEVELCLASS(leveldir_current))
1651       {
1652         case LEVELCLASS_TUTORIAL:
1653           strcpy(level->author, PROGRAM_AUTHOR_STRING);
1654           break;
1655
1656         case LEVELCLASS_CONTRIB:
1657           strncpy(level->author, leveldir_current->name, MAX_LEVEL_AUTHOR_LEN);
1658           level->author[MAX_LEVEL_AUTHOR_LEN] = '\0';
1659           break;
1660
1661         case LEVELCLASS_PRIVATE:
1662           strncpy(level->author, getRealName(), MAX_LEVEL_AUTHOR_LEN);
1663           level->author[MAX_LEVEL_AUTHOR_LEN] = '\0';
1664           break;
1665
1666         default:
1667           /* keep default value */
1668           break;
1669       }
1670     }
1671   }
1672 }
1673
1674 static void setLevelInfoToDefaults_Elements(struct LevelInfo *level)
1675 {
1676   static boolean clipboard_elements_initialized = FALSE;
1677   int i;
1678
1679   InitElementPropertiesStatic();
1680
1681   li = *level;          /* copy level data into temporary buffer */
1682   setConfigToDefaultsFromConfigList(chunk_config_ELEM);
1683   *level = li;          /* copy temporary buffer back to level data */
1684
1685   for (i = 0; i < MAX_NUM_ELEMENTS; i++)
1686   {
1687     int element = i;
1688     struct ElementInfo *ei = &element_info[element];
1689
1690     /* never initialize clipboard elements after the very first time */
1691     /* (to be able to use clipboard elements between several levels) */
1692     if (IS_CLIPBOARD_ELEMENT(element) && clipboard_elements_initialized)
1693       continue;
1694
1695     if (IS_ENVELOPE(element))
1696     {
1697       int envelope_nr = element - EL_ENVELOPE_1;
1698
1699       setConfigToDefaultsFromConfigList(chunk_config_NOTE);
1700
1701       level->envelope[envelope_nr] = xx_envelope;
1702     }
1703
1704     if (IS_CUSTOM_ELEMENT(element) ||
1705         IS_GROUP_ELEMENT(element) ||
1706         IS_INTERNAL_ELEMENT(element))
1707     {
1708       xx_ei = *ei;      /* copy element data into temporary buffer */
1709
1710       setConfigToDefaultsFromConfigList(chunk_config_CUSX_base);
1711
1712       *ei = xx_ei;
1713     }
1714
1715     setElementChangePages(ei, 1);
1716     setElementChangeInfoToDefaults(ei->change);
1717
1718     if (IS_CUSTOM_ELEMENT(element) ||
1719         IS_GROUP_ELEMENT(element) ||
1720         IS_INTERNAL_ELEMENT(element))
1721     {
1722       setElementDescriptionToDefault(ei);
1723
1724       ei->modified_settings = FALSE;
1725     }
1726
1727     if (IS_CUSTOM_ELEMENT(element) ||
1728         IS_INTERNAL_ELEMENT(element))
1729     {
1730       /* internal values used in level editor */
1731
1732       ei->access_type = 0;
1733       ei->access_layer = 0;
1734       ei->access_protected = 0;
1735       ei->walk_to_action = 0;
1736       ei->smash_targets = 0;
1737       ei->deadliness = 0;
1738
1739       ei->can_explode_by_fire = FALSE;
1740       ei->can_explode_smashed = FALSE;
1741       ei->can_explode_impact = FALSE;
1742
1743       ei->current_change_page = 0;
1744     }
1745
1746     if (IS_GROUP_ELEMENT(element) ||
1747         IS_INTERNAL_ELEMENT(element))
1748     {
1749       struct ElementGroupInfo *group;
1750
1751       /* initialize memory for list of elements in group */
1752       if (ei->group == NULL)
1753         ei->group = checked_malloc(sizeof(struct ElementGroupInfo));
1754
1755       group = ei->group;
1756
1757       xx_group = *group;        /* copy group data into temporary buffer */
1758
1759       setConfigToDefaultsFromConfigList(chunk_config_GRPX);
1760
1761       *group = xx_group;
1762     }
1763   }
1764
1765   clipboard_elements_initialized = TRUE;
1766 }
1767
1768 static void setLevelInfoToDefaults(struct LevelInfo *level,
1769                                    boolean level_info_only,
1770                                    boolean reset_file_status)
1771 {
1772   setLevelInfoToDefaults_Level(level);
1773
1774   if (!level_info_only)
1775     setLevelInfoToDefaults_Elements(level);
1776
1777   if (reset_file_status)
1778   {
1779     level->no_valid_file = FALSE;
1780     level->no_level_file = FALSE;
1781   }
1782
1783   level->changed = FALSE;
1784 }
1785
1786 static void setFileInfoToDefaults(struct LevelFileInfo *level_file_info)
1787 {
1788   level_file_info->nr = 0;
1789   level_file_info->type = LEVEL_FILE_TYPE_UNKNOWN;
1790   level_file_info->packed = FALSE;
1791   level_file_info->basename = NULL;
1792   level_file_info->filename = NULL;
1793 }
1794
1795 int getMappedElement_SB(int, boolean);
1796
1797 static void ActivateLevelTemplate()
1798 {
1799   int x, y;
1800
1801   if (check_special_flags("load_xsb_to_ces"))
1802   {
1803     /* fill smaller playfields with padding "beyond border wall" elements */
1804     if (level.fieldx < level_template.fieldx ||
1805         level.fieldy < level_template.fieldy)
1806     {
1807       short field[level.fieldx][level.fieldy];
1808       int new_fieldx = MAX(level.fieldx, level_template.fieldx);
1809       int new_fieldy = MAX(level.fieldy, level_template.fieldy);
1810       int pos_fieldx = (new_fieldx - level.fieldx) / 2;
1811       int pos_fieldy = (new_fieldy - level.fieldy) / 2;
1812
1813       /* copy old playfield (which is smaller than the visible area) */
1814       for (y = 0; y < level.fieldy; y++) for (x = 0; x < level.fieldx; x++)
1815         field[x][y] = level.field[x][y];
1816
1817       /* fill new, larger playfield with "beyond border wall" elements */
1818       for (y = 0; y < new_fieldy; y++) for (x = 0; x < new_fieldx; x++)
1819         level.field[x][y] = getMappedElement_SB('_', TRUE);
1820
1821       /* copy the old playfield to the middle of the new playfield */
1822       for (y = 0; y < level.fieldy; y++) for (x = 0; x < level.fieldx; x++)
1823         level.field[pos_fieldx + x][pos_fieldy + y] = field[x][y];
1824
1825       level.fieldx = new_fieldx;
1826       level.fieldy = new_fieldy;
1827     }
1828   }
1829
1830   /* Currently there is no special action needed to activate the template
1831      data, because 'element_info' property settings overwrite the original
1832      level data, while all other variables do not change. */
1833
1834   /* Exception: 'from_level_template' elements in the original level playfield
1835      are overwritten with the corresponding elements at the same position in
1836      playfield from the level template. */
1837
1838   for (x = 0; x < level.fieldx; x++)
1839     for (y = 0; y < level.fieldy; y++)
1840       if (level.field[x][y] == EL_FROM_LEVEL_TEMPLATE)
1841         level.field[x][y] = level_template.field[x][y];
1842
1843   if (check_special_flags("load_xsb_to_ces"))
1844   {
1845     struct LevelInfo level_backup = level;
1846
1847     /* overwrite all individual level settings from template level settings */
1848     level = level_template;
1849
1850     /* restore playfield size */
1851     level.fieldx = level_backup.fieldx;
1852     level.fieldy = level_backup.fieldy;
1853
1854     /* restore playfield content */
1855     for (x = 0; x < level.fieldx; x++)
1856       for (y = 0; y < level.fieldy; y++)
1857         level.field[x][y] = level_backup.field[x][y];
1858
1859     /* restore name and author from individual level */
1860     strcpy(level.name,   level_backup.name);
1861     strcpy(level.author, level_backup.author);
1862
1863     /* restore flag "use_custom_template" */
1864     level.use_custom_template = level_backup.use_custom_template;
1865   }
1866 }
1867
1868 static char *getLevelFilenameFromBasename(char *basename)
1869 {
1870   static char *filename[2] = { NULL, NULL };
1871   int pos = (strEqual(basename, LEVELTEMPLATE_FILENAME) ? 0 : 1);
1872
1873   checked_free(filename[pos]);
1874
1875   filename[pos] = getPath2(getCurrentLevelDir(), basename);
1876
1877   return filename[pos];
1878 }
1879
1880 static int getFileTypeFromBasename(char *basename)
1881 {
1882   /* !!! ALSO SEE COMMENT IN checkForPackageFromBasename() !!! */
1883
1884   static char *filename = NULL;
1885   struct stat file_status;
1886
1887   /* ---------- try to determine file type from filename ---------- */
1888
1889   /* check for typical filename of a Supaplex level package file */
1890   if (strlen(basename) == 10 && strPrefixLower(basename, "levels.d"))
1891     return LEVEL_FILE_TYPE_SP;
1892
1893   /* check for typical filename of a Diamond Caves II level package file */
1894   if (strSuffixLower(basename, ".dc") ||
1895       strSuffixLower(basename, ".dc2"))
1896     return LEVEL_FILE_TYPE_DC;
1897
1898   /* check for typical filename of a Sokoban level package file */
1899   if (strSuffixLower(basename, ".xsb") &&
1900       strchr(basename, '%') == NULL)
1901     return LEVEL_FILE_TYPE_SB;
1902
1903   /* ---------- try to determine file type from filesize ---------- */
1904
1905   checked_free(filename);
1906   filename = getPath2(getCurrentLevelDir(), basename);
1907
1908   if (stat(filename, &file_status) == 0)
1909   {
1910     /* check for typical filesize of a Supaplex level package file */
1911     if (file_status.st_size == 170496)
1912       return LEVEL_FILE_TYPE_SP;
1913   }
1914
1915   return LEVEL_FILE_TYPE_UNKNOWN;
1916 }
1917
1918 static boolean checkForPackageFromBasename(char *basename)
1919 {
1920   /* !!! WON'T WORK ANYMORE IF getFileTypeFromBasename() ALSO DETECTS !!!
1921      !!! SINGLE LEVELS (CURRENTLY ONLY DETECTS LEVEL PACKAGES         !!! */
1922
1923   return (getFileTypeFromBasename(basename) != LEVEL_FILE_TYPE_UNKNOWN);
1924 }
1925
1926 static char *getSingleLevelBasenameExt(int nr, char *extension)
1927 {
1928   static char basename[MAX_FILENAME_LEN];
1929
1930   if (nr < 0)
1931     sprintf(basename, "%s", LEVELTEMPLATE_FILENAME);
1932   else
1933     sprintf(basename, "%03d.%s", nr, extension);
1934
1935   return basename;
1936 }
1937
1938 static char *getSingleLevelBasename(int nr)
1939 {
1940   return getSingleLevelBasenameExt(nr, LEVELFILE_EXTENSION);
1941 }
1942
1943 static char *getPackedLevelBasename(int type)
1944 {
1945   static char basename[MAX_FILENAME_LEN];
1946   char *directory = getCurrentLevelDir();
1947   Directory *dir;
1948   DirectoryEntry *dir_entry;
1949
1950   strcpy(basename, UNDEFINED_FILENAME);         /* default: undefined file */
1951
1952   if ((dir = openDirectory(directory)) == NULL)
1953   {
1954     Error(ERR_WARN, "cannot read current level directory '%s'", directory);
1955
1956     return basename;
1957   }
1958
1959   while ((dir_entry = readDirectory(dir)) != NULL)      /* loop all entries */
1960   {
1961     char *entry_basename = dir_entry->basename;
1962     int entry_type = getFileTypeFromBasename(entry_basename);
1963
1964     if (entry_type != LEVEL_FILE_TYPE_UNKNOWN)  /* found valid level package */
1965     {
1966       if (type == LEVEL_FILE_TYPE_UNKNOWN ||
1967           type == entry_type)
1968       {
1969         strcpy(basename, entry_basename);
1970
1971         break;
1972       }
1973     }
1974   }
1975
1976   closeDirectory(dir);
1977
1978   return basename;
1979 }
1980
1981 static char *getSingleLevelFilename(int nr)
1982 {
1983   return getLevelFilenameFromBasename(getSingleLevelBasename(nr));
1984 }
1985
1986 #if ENABLE_UNUSED_CODE
1987 static char *getPackedLevelFilename(int type)
1988 {
1989   return getLevelFilenameFromBasename(getPackedLevelBasename(type));
1990 }
1991 #endif
1992
1993 char *getDefaultLevelFilename(int nr)
1994 {
1995   return getSingleLevelFilename(nr);
1996 }
1997
1998 #if ENABLE_UNUSED_CODE
1999 static void setLevelFileInfo_SingleLevelFilename(struct LevelFileInfo *lfi,
2000                                                  int type)
2001 {
2002   lfi->type = type;
2003   lfi->packed = FALSE;
2004   lfi->basename = getSingleLevelBasename(lfi->nr, lfi->type);
2005   lfi->filename = getLevelFilenameFromBasename(lfi->basename);
2006 }
2007 #endif
2008
2009 static void setLevelFileInfo_FormatLevelFilename(struct LevelFileInfo *lfi,
2010                                                  int type, char *format, ...)
2011 {
2012   static char basename[MAX_FILENAME_LEN];
2013   va_list ap;
2014
2015   va_start(ap, format);
2016   vsprintf(basename, format, ap);
2017   va_end(ap);
2018
2019   lfi->type = type;
2020   lfi->packed = FALSE;
2021   lfi->basename = basename;
2022   lfi->filename = getLevelFilenameFromBasename(lfi->basename);
2023 }
2024
2025 static void setLevelFileInfo_PackedLevelFilename(struct LevelFileInfo *lfi,
2026                                                  int type)
2027 {
2028   lfi->type = type;
2029   lfi->packed = TRUE;
2030   lfi->basename = getPackedLevelBasename(lfi->type);
2031   lfi->filename = getLevelFilenameFromBasename(lfi->basename);
2032 }
2033
2034 static int getFiletypeFromID(char *filetype_id)
2035 {
2036   char *filetype_id_lower;
2037   int filetype = LEVEL_FILE_TYPE_UNKNOWN;
2038   int i;
2039
2040   if (filetype_id == NULL)
2041     return LEVEL_FILE_TYPE_UNKNOWN;
2042
2043   filetype_id_lower = getStringToLower(filetype_id);
2044
2045   for (i = 0; filetype_id_list[i].id != NULL; i++)
2046   {
2047     char *id_lower = getStringToLower(filetype_id_list[i].id);
2048     
2049     if (strEqual(filetype_id_lower, id_lower))
2050       filetype = filetype_id_list[i].filetype;
2051
2052     free(id_lower);
2053
2054     if (filetype != LEVEL_FILE_TYPE_UNKNOWN)
2055       break;
2056   }
2057
2058   free(filetype_id_lower);
2059
2060   return filetype;
2061 }
2062
2063 char *getLocalLevelTemplateFilename()
2064 {
2065   return getDefaultLevelFilename(-1);
2066 }
2067
2068 char *getGlobalLevelTemplateFilename()
2069 {
2070   /* global variable "leveldir_current" must be modified in the loop below */
2071   LevelDirTree *leveldir_current_last = leveldir_current;
2072   char *filename = NULL;
2073
2074   /* check for template level in path from current to topmost tree node */
2075
2076   while (leveldir_current != NULL)
2077   {
2078     filename = getDefaultLevelFilename(-1);
2079
2080     if (fileExists(filename))
2081       break;
2082
2083     leveldir_current = leveldir_current->node_parent;
2084   }
2085
2086   /* restore global variable "leveldir_current" modified in above loop */
2087   leveldir_current = leveldir_current_last;
2088
2089   return filename;
2090 }
2091
2092 static void determineLevelFileInfo_Filename(struct LevelFileInfo *lfi)
2093 {
2094   int nr = lfi->nr;
2095
2096   /* special case: level number is negative => check for level template file */
2097   if (nr < 0)
2098   {
2099     setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_RND,
2100                                          getSingleLevelBasename(-1));
2101
2102     /* replace local level template filename with global template filename */
2103     lfi->filename = getGlobalLevelTemplateFilename();
2104
2105     /* no fallback if template file not existing */
2106     return;
2107   }
2108
2109   /* special case: check for file name/pattern specified in "levelinfo.conf" */
2110   if (leveldir_current->level_filename != NULL)
2111   {
2112     int filetype = getFiletypeFromID(leveldir_current->level_filetype);
2113
2114     setLevelFileInfo_FormatLevelFilename(lfi, filetype,
2115                                          leveldir_current->level_filename, nr);
2116
2117     lfi->packed = checkForPackageFromBasename(leveldir_current->level_filename);
2118
2119     if (fileExists(lfi->filename))
2120       return;
2121   }
2122
2123   /* check for native Rocks'n'Diamonds level file */
2124   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_RND,
2125                                        "%03d.%s", nr, LEVELFILE_EXTENSION);
2126   if (fileExists(lfi->filename))
2127     return;
2128
2129   /* check for Emerald Mine level file (V1) */
2130   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "a%c%c",
2131                                        'a' + (nr / 10) % 26, '0' + nr % 10);
2132   if (fileExists(lfi->filename))
2133     return;
2134   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "A%c%c",
2135                                        'A' + (nr / 10) % 26, '0' + nr % 10);
2136   if (fileExists(lfi->filename))
2137     return;
2138
2139   /* check for Emerald Mine level file (V2 to V5) */
2140   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "%d", nr);
2141   if (fileExists(lfi->filename))
2142     return;
2143
2144   /* check for Emerald Mine level file (V6 / single mode) */
2145   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "%02ds", nr);
2146   if (fileExists(lfi->filename))
2147     return;
2148   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "%02dS", nr);
2149   if (fileExists(lfi->filename))
2150     return;
2151
2152   /* check for Emerald Mine level file (V6 / teamwork mode) */
2153   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "%02dt", nr);
2154   if (fileExists(lfi->filename))
2155     return;
2156   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "%02dT", nr);
2157   if (fileExists(lfi->filename))
2158     return;
2159
2160   /* check for various packed level file formats */
2161   setLevelFileInfo_PackedLevelFilename(lfi, LEVEL_FILE_TYPE_UNKNOWN);
2162   if (fileExists(lfi->filename))
2163     return;
2164
2165   /* no known level file found -- use default values (and fail later) */
2166   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_RND,
2167                                        "%03d.%s", nr, LEVELFILE_EXTENSION);
2168 }
2169
2170 static void determineLevelFileInfo_Filetype(struct LevelFileInfo *lfi)
2171 {
2172   if (lfi->type == LEVEL_FILE_TYPE_UNKNOWN)
2173     lfi->type = getFileTypeFromBasename(lfi->basename);
2174 }
2175
2176 static void setLevelFileInfo(struct LevelFileInfo *level_file_info, int nr)
2177 {
2178   /* always start with reliable default values */
2179   setFileInfoToDefaults(level_file_info);
2180
2181   level_file_info->nr = nr;     /* set requested level number */
2182
2183   determineLevelFileInfo_Filename(level_file_info);
2184   determineLevelFileInfo_Filetype(level_file_info);
2185 }
2186
2187 /* ------------------------------------------------------------------------- */
2188 /* functions for loading R'n'D level                                         */
2189 /* ------------------------------------------------------------------------- */
2190
2191 int getMappedElement(int element)
2192 {
2193   /* remap some (historic, now obsolete) elements */
2194
2195   switch (element)
2196   {
2197     case EL_PLAYER_OBSOLETE:
2198       element = EL_PLAYER_1;
2199       break;
2200
2201     case EL_KEY_OBSOLETE:
2202       element = EL_KEY_1;
2203       break;
2204
2205     case EL_EM_KEY_1_FILE_OBSOLETE:
2206       element = EL_EM_KEY_1;
2207       break;
2208
2209     case EL_EM_KEY_2_FILE_OBSOLETE:
2210       element = EL_EM_KEY_2;
2211       break;
2212
2213     case EL_EM_KEY_3_FILE_OBSOLETE:
2214       element = EL_EM_KEY_3;
2215       break;
2216
2217     case EL_EM_KEY_4_FILE_OBSOLETE:
2218       element = EL_EM_KEY_4;
2219       break;
2220
2221     case EL_ENVELOPE_OBSOLETE:
2222       element = EL_ENVELOPE_1;
2223       break;
2224
2225     case EL_SP_EMPTY:
2226       element = EL_EMPTY;
2227       break;
2228
2229     default:
2230       if (element >= NUM_FILE_ELEMENTS)
2231       {
2232         Error(ERR_WARN, "invalid level element %d", element);
2233
2234         element = EL_UNKNOWN;
2235       }
2236       break;
2237   }
2238
2239   return element;
2240 }
2241
2242 int getMappedElementByVersion(int element, int game_version)
2243 {
2244   /* remap some elements due to certain game version */
2245
2246   if (game_version <= VERSION_IDENT(2,2,0,0))
2247   {
2248     /* map game font elements */
2249     element = (element == EL_CHAR('[')  ? EL_CHAR_AUMLAUT :
2250                element == EL_CHAR('\\') ? EL_CHAR_OUMLAUT :
2251                element == EL_CHAR(']')  ? EL_CHAR_UUMLAUT :
2252                element == EL_CHAR('^')  ? EL_CHAR_COPYRIGHT : element);
2253   }
2254
2255   if (game_version < VERSION_IDENT(3,0,0,0))
2256   {
2257     /* map Supaplex gravity tube elements */
2258     element = (element == EL_SP_GRAVITY_PORT_LEFT  ? EL_SP_PORT_LEFT  :
2259                element == EL_SP_GRAVITY_PORT_RIGHT ? EL_SP_PORT_RIGHT :
2260                element == EL_SP_GRAVITY_PORT_UP    ? EL_SP_PORT_UP    :
2261                element == EL_SP_GRAVITY_PORT_DOWN  ? EL_SP_PORT_DOWN  :
2262                element);
2263   }
2264
2265   return element;
2266 }
2267
2268 static int LoadLevel_VERS(File *file, int chunk_size, struct LevelInfo *level)
2269 {
2270   level->file_version = getFileVersion(file);
2271   level->game_version = getFileVersion(file);
2272
2273   return chunk_size;
2274 }
2275
2276 static int LoadLevel_DATE(File *file, int chunk_size, struct LevelInfo *level)
2277 {
2278   level->creation_date.year  = getFile16BitBE(file);
2279   level->creation_date.month = getFile8Bit(file);
2280   level->creation_date.day   = getFile8Bit(file);
2281
2282   level->creation_date.src   = DATE_SRC_LEVELFILE;
2283
2284   return chunk_size;
2285 }
2286
2287 static int LoadLevel_HEAD(File *file, int chunk_size, struct LevelInfo *level)
2288 {
2289   int initial_player_stepsize;
2290   int initial_player_gravity;
2291   int i, x, y;
2292
2293   level->fieldx = getFile8Bit(file);
2294   level->fieldy = getFile8Bit(file);
2295
2296   level->time           = getFile16BitBE(file);
2297   level->gems_needed    = getFile16BitBE(file);
2298
2299   for (i = 0; i < MAX_LEVEL_NAME_LEN; i++)
2300     level->name[i] = getFile8Bit(file);
2301   level->name[MAX_LEVEL_NAME_LEN] = 0;
2302
2303   for (i = 0; i < LEVEL_SCORE_ELEMENTS; i++)
2304     level->score[i] = getFile8Bit(file);
2305
2306   level->num_yamyam_contents = STD_ELEMENT_CONTENTS;
2307   for (i = 0; i < STD_ELEMENT_CONTENTS; i++)
2308     for (y = 0; y < 3; y++)
2309       for (x = 0; x < 3; x++)
2310         level->yamyam_content[i].e[x][y] = getMappedElement(getFile8Bit(file));
2311
2312   level->amoeba_speed           = getFile8Bit(file);
2313   level->time_magic_wall        = getFile8Bit(file);
2314   level->time_wheel             = getFile8Bit(file);
2315   level->amoeba_content         = getMappedElement(getFile8Bit(file));
2316
2317   initial_player_stepsize       = (getFile8Bit(file) == 1 ? STEPSIZE_FAST :
2318                                    STEPSIZE_NORMAL);
2319
2320   for (i = 0; i < MAX_PLAYERS; i++)
2321     level->initial_player_stepsize[i] = initial_player_stepsize;
2322
2323   initial_player_gravity        = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2324
2325   for (i = 0; i < MAX_PLAYERS; i++)
2326     level->initial_player_gravity[i] = initial_player_gravity;
2327
2328   level->encoding_16bit_field   = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2329   level->em_slippery_gems       = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2330
2331   level->use_custom_template    = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2332
2333   level->block_last_field       = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2334   level->sp_block_last_field    = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2335   level->can_move_into_acid_bits = getFile32BitBE(file);
2336   level->dont_collide_with_bits = getFile8Bit(file);
2337
2338   level->use_spring_bug         = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2339   level->use_step_counter       = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2340
2341   level->instant_relocation     = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2342   level->can_pass_to_walkable   = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2343   level->grow_into_diggable     = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2344
2345   level->game_engine_type       = getFile8Bit(file);
2346
2347   ReadUnusedBytesFromFile(file, LEVEL_CHUNK_HEAD_UNUSED);
2348
2349   return chunk_size;
2350 }
2351
2352 static int LoadLevel_NAME(File *file, int chunk_size, struct LevelInfo *level)
2353 {
2354   int i;
2355
2356   for (i = 0; i < MAX_LEVEL_NAME_LEN; i++)
2357     level->name[i] = getFile8Bit(file);
2358   level->name[MAX_LEVEL_NAME_LEN] = 0;
2359
2360   return chunk_size;
2361 }
2362
2363 static int LoadLevel_AUTH(File *file, int chunk_size, struct LevelInfo *level)
2364 {
2365   int i;
2366
2367   for (i = 0; i < MAX_LEVEL_AUTHOR_LEN; i++)
2368     level->author[i] = getFile8Bit(file);
2369   level->author[MAX_LEVEL_AUTHOR_LEN] = 0;
2370
2371   return chunk_size;
2372 }
2373
2374 static int LoadLevel_BODY(File *file, int chunk_size, struct LevelInfo *level)
2375 {
2376   int x, y;
2377   int chunk_size_expected = level->fieldx * level->fieldy;
2378
2379   /* Note: "chunk_size" was wrong before version 2.0 when elements are
2380      stored with 16-bit encoding (and should be twice as big then).
2381      Even worse, playfield data was stored 16-bit when only yamyam content
2382      contained 16-bit elements and vice versa. */
2383
2384   if (level->encoding_16bit_field && level->file_version >= FILE_VERSION_2_0)
2385     chunk_size_expected *= 2;
2386
2387   if (chunk_size_expected != chunk_size)
2388   {
2389     ReadUnusedBytesFromFile(file, chunk_size);
2390     return chunk_size_expected;
2391   }
2392
2393   for (y = 0; y < level->fieldy; y++)
2394     for (x = 0; x < level->fieldx; x++)
2395       level->field[x][y] =
2396         getMappedElement(level->encoding_16bit_field ? getFile16BitBE(file) :
2397                          getFile8Bit(file));
2398   return chunk_size;
2399 }
2400
2401 static int LoadLevel_CONT(File *file, int chunk_size, struct LevelInfo *level)
2402 {
2403   int i, x, y;
2404   int header_size = 4;
2405   int content_size = MAX_ELEMENT_CONTENTS * 3 * 3;
2406   int chunk_size_expected = header_size + content_size;
2407
2408   /* Note: "chunk_size" was wrong before version 2.0 when elements are
2409      stored with 16-bit encoding (and should be twice as big then).
2410      Even worse, playfield data was stored 16-bit when only yamyam content
2411      contained 16-bit elements and vice versa. */
2412
2413   if (level->encoding_16bit_field && level->file_version >= FILE_VERSION_2_0)
2414     chunk_size_expected += content_size;
2415
2416   if (chunk_size_expected != chunk_size)
2417   {
2418     ReadUnusedBytesFromFile(file, chunk_size);
2419     return chunk_size_expected;
2420   }
2421
2422   getFile8Bit(file);
2423   level->num_yamyam_contents = getFile8Bit(file);
2424   getFile8Bit(file);
2425   getFile8Bit(file);
2426
2427   /* correct invalid number of content fields -- should never happen */
2428   if (level->num_yamyam_contents < 1 ||
2429       level->num_yamyam_contents > MAX_ELEMENT_CONTENTS)
2430     level->num_yamyam_contents = STD_ELEMENT_CONTENTS;
2431
2432   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
2433     for (y = 0; y < 3; y++)
2434       for (x = 0; x < 3; x++)
2435         level->yamyam_content[i].e[x][y] =
2436           getMappedElement(level->encoding_16bit_field ?
2437                            getFile16BitBE(file) : getFile8Bit(file));
2438   return chunk_size;
2439 }
2440
2441 static int LoadLevel_CNT2(File *file, int chunk_size, struct LevelInfo *level)
2442 {
2443   int i, x, y;
2444   int element;
2445   int num_contents;
2446   int content_array[MAX_ELEMENT_CONTENTS][3][3];
2447
2448   element = getMappedElement(getFile16BitBE(file));
2449   num_contents = getFile8Bit(file);
2450
2451   getFile8Bit(file);    /* content x size (unused) */
2452   getFile8Bit(file);    /* content y size (unused) */
2453
2454   ReadUnusedBytesFromFile(file, LEVEL_CHUNK_CNT2_UNUSED);
2455
2456   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
2457     for (y = 0; y < 3; y++)
2458       for (x = 0; x < 3; x++)
2459         content_array[i][x][y] = getMappedElement(getFile16BitBE(file));
2460
2461   /* correct invalid number of content fields -- should never happen */
2462   if (num_contents < 1 || num_contents > MAX_ELEMENT_CONTENTS)
2463     num_contents = STD_ELEMENT_CONTENTS;
2464
2465   if (element == EL_YAMYAM)
2466   {
2467     level->num_yamyam_contents = num_contents;
2468
2469     for (i = 0; i < num_contents; i++)
2470       for (y = 0; y < 3; y++)
2471         for (x = 0; x < 3; x++)
2472           level->yamyam_content[i].e[x][y] = content_array[i][x][y];
2473   }
2474   else if (element == EL_BD_AMOEBA)
2475   {
2476     level->amoeba_content = content_array[0][0][0];
2477   }
2478   else
2479   {
2480     Error(ERR_WARN, "cannot load content for element '%d'", element);
2481   }
2482
2483   return chunk_size;
2484 }
2485
2486 static int LoadLevel_CNT3(File *file, int chunk_size, struct LevelInfo *level)
2487 {
2488   int i;
2489   int element;
2490   int envelope_nr;
2491   int envelope_len;
2492   int chunk_size_expected;
2493
2494   element = getMappedElement(getFile16BitBE(file));
2495   if (!IS_ENVELOPE(element))
2496     element = EL_ENVELOPE_1;
2497
2498   envelope_nr = element - EL_ENVELOPE_1;
2499
2500   envelope_len = getFile16BitBE(file);
2501
2502   level->envelope[envelope_nr].xsize = getFile8Bit(file);
2503   level->envelope[envelope_nr].ysize = getFile8Bit(file);
2504
2505   ReadUnusedBytesFromFile(file, LEVEL_CHUNK_CNT3_UNUSED);
2506
2507   chunk_size_expected = LEVEL_CHUNK_CNT3_SIZE(envelope_len);
2508   if (chunk_size_expected != chunk_size)
2509   {
2510     ReadUnusedBytesFromFile(file, chunk_size - LEVEL_CHUNK_CNT3_HEADER);
2511     return chunk_size_expected;
2512   }
2513
2514   for (i = 0; i < envelope_len; i++)
2515     level->envelope[envelope_nr].text[i] = getFile8Bit(file);
2516
2517   return chunk_size;
2518 }
2519
2520 static int LoadLevel_CUS1(File *file, int chunk_size, struct LevelInfo *level)
2521 {
2522   int num_changed_custom_elements = getFile16BitBE(file);
2523   int chunk_size_expected = 2 + num_changed_custom_elements * 6;
2524   int i;
2525
2526   if (chunk_size_expected != chunk_size)
2527   {
2528     ReadUnusedBytesFromFile(file, chunk_size - 2);
2529     return chunk_size_expected;
2530   }
2531
2532   for (i = 0; i < num_changed_custom_elements; i++)
2533   {
2534     int element = getMappedElement(getFile16BitBE(file));
2535     int properties = getFile32BitBE(file);
2536
2537     if (IS_CUSTOM_ELEMENT(element))
2538       element_info[element].properties[EP_BITFIELD_BASE_NR] = properties;
2539     else
2540       Error(ERR_WARN, "invalid custom element number %d", element);
2541
2542     /* older game versions that wrote level files with CUS1 chunks used
2543        different default push delay values (not yet stored in level file) */
2544     element_info[element].push_delay_fixed = 2;
2545     element_info[element].push_delay_random = 8;
2546   }
2547
2548   return chunk_size;
2549 }
2550
2551 static int LoadLevel_CUS2(File *file, int chunk_size, struct LevelInfo *level)
2552 {
2553   int num_changed_custom_elements = getFile16BitBE(file);
2554   int chunk_size_expected = 2 + num_changed_custom_elements * 4;
2555   int i;
2556
2557   if (chunk_size_expected != chunk_size)
2558   {
2559     ReadUnusedBytesFromFile(file, chunk_size - 2);
2560     return chunk_size_expected;
2561   }
2562
2563   for (i = 0; i < num_changed_custom_elements; i++)
2564   {
2565     int element = getMappedElement(getFile16BitBE(file));
2566     int custom_target_element = getMappedElement(getFile16BitBE(file));
2567
2568     if (IS_CUSTOM_ELEMENT(element))
2569       element_info[element].change->target_element = custom_target_element;
2570     else
2571       Error(ERR_WARN, "invalid custom element number %d", element);
2572   }
2573
2574   return chunk_size;
2575 }
2576
2577 static int LoadLevel_CUS3(File *file, int chunk_size, struct LevelInfo *level)
2578 {
2579   int num_changed_custom_elements = getFile16BitBE(file);
2580   int chunk_size_expected = LEVEL_CHUNK_CUS3_SIZE(num_changed_custom_elements);
2581   int i, j, x, y;
2582
2583   if (chunk_size_expected != chunk_size)
2584   {
2585     ReadUnusedBytesFromFile(file, chunk_size - 2);
2586     return chunk_size_expected;
2587   }
2588
2589   for (i = 0; i < num_changed_custom_elements; i++)
2590   {
2591     int element = getMappedElement(getFile16BitBE(file));
2592     struct ElementInfo *ei = &element_info[element];
2593     unsigned int event_bits;
2594
2595     if (!IS_CUSTOM_ELEMENT(element))
2596     {
2597       Error(ERR_WARN, "invalid custom element number %d", element);
2598
2599       element = EL_INTERNAL_DUMMY;
2600     }
2601
2602     for (j = 0; j < MAX_ELEMENT_NAME_LEN; j++)
2603       ei->description[j] = getFile8Bit(file);
2604     ei->description[MAX_ELEMENT_NAME_LEN] = 0;
2605
2606     ei->properties[EP_BITFIELD_BASE_NR] = getFile32BitBE(file);
2607
2608     /* some free bytes for future properties and padding */
2609     ReadUnusedBytesFromFile(file, 7);
2610
2611     ei->use_gfx_element = getFile8Bit(file);
2612     ei->gfx_element_initial = getMappedElement(getFile16BitBE(file));
2613
2614     ei->collect_score_initial = getFile8Bit(file);
2615     ei->collect_count_initial = getFile8Bit(file);
2616
2617     ei->push_delay_fixed = getFile16BitBE(file);
2618     ei->push_delay_random = getFile16BitBE(file);
2619     ei->move_delay_fixed = getFile16BitBE(file);
2620     ei->move_delay_random = getFile16BitBE(file);
2621
2622     ei->move_pattern = getFile16BitBE(file);
2623     ei->move_direction_initial = getFile8Bit(file);
2624     ei->move_stepsize = getFile8Bit(file);
2625
2626     for (y = 0; y < 3; y++)
2627       for (x = 0; x < 3; x++)
2628         ei->content.e[x][y] = getMappedElement(getFile16BitBE(file));
2629
2630     event_bits = getFile32BitBE(file);
2631     for (j = 0; j < NUM_CHANGE_EVENTS; j++)
2632       if (event_bits & (1 << j))
2633         ei->change->has_event[j] = TRUE;
2634
2635     ei->change->target_element = getMappedElement(getFile16BitBE(file));
2636
2637     ei->change->delay_fixed = getFile16BitBE(file);
2638     ei->change->delay_random = getFile16BitBE(file);
2639     ei->change->delay_frames = getFile16BitBE(file);
2640
2641     ei->change->initial_trigger_element= getMappedElement(getFile16BitBE(file));
2642
2643     ei->change->explode = getFile8Bit(file);
2644     ei->change->use_target_content = getFile8Bit(file);
2645     ei->change->only_if_complete = getFile8Bit(file);
2646     ei->change->use_random_replace = getFile8Bit(file);
2647
2648     ei->change->random_percentage = getFile8Bit(file);
2649     ei->change->replace_when = getFile8Bit(file);
2650
2651     for (y = 0; y < 3; y++)
2652       for (x = 0; x < 3; x++)
2653         ei->change->target_content.e[x][y] =
2654           getMappedElement(getFile16BitBE(file));
2655
2656     ei->slippery_type = getFile8Bit(file);
2657
2658     /* some free bytes for future properties and padding */
2659     ReadUnusedBytesFromFile(file, LEVEL_CPART_CUS3_UNUSED);
2660
2661     /* mark that this custom element has been modified */
2662     ei->modified_settings = TRUE;
2663   }
2664
2665   return chunk_size;
2666 }
2667
2668 static int LoadLevel_CUS4(File *file, int chunk_size, struct LevelInfo *level)
2669 {
2670   struct ElementInfo *ei;
2671   int chunk_size_expected;
2672   int element;
2673   int i, j, x, y;
2674
2675   /* ---------- custom element base property values (96 bytes) ------------- */
2676
2677   element = getMappedElement(getFile16BitBE(file));
2678
2679   if (!IS_CUSTOM_ELEMENT(element))
2680   {
2681     Error(ERR_WARN, "invalid custom element number %d", element);
2682
2683     ReadUnusedBytesFromFile(file, chunk_size - 2);
2684     return chunk_size;
2685   }
2686
2687   ei = &element_info[element];
2688
2689   for (i = 0; i < MAX_ELEMENT_NAME_LEN; i++)
2690     ei->description[i] = getFile8Bit(file);
2691   ei->description[MAX_ELEMENT_NAME_LEN] = 0;
2692
2693   ei->properties[EP_BITFIELD_BASE_NR] = getFile32BitBE(file);
2694
2695   ReadUnusedBytesFromFile(file, 4);     /* reserved for more base properties */
2696
2697   ei->num_change_pages = getFile8Bit(file);
2698
2699   chunk_size_expected = LEVEL_CHUNK_CUS4_SIZE(ei->num_change_pages);
2700   if (chunk_size_expected != chunk_size)
2701   {
2702     ReadUnusedBytesFromFile(file, chunk_size - 43);
2703     return chunk_size_expected;
2704   }
2705
2706   ei->ce_value_fixed_initial = getFile16BitBE(file);
2707   ei->ce_value_random_initial = getFile16BitBE(file);
2708   ei->use_last_ce_value = getFile8Bit(file);
2709
2710   ei->use_gfx_element = getFile8Bit(file);
2711   ei->gfx_element_initial = getMappedElement(getFile16BitBE(file));
2712
2713   ei->collect_score_initial = getFile8Bit(file);
2714   ei->collect_count_initial = getFile8Bit(file);
2715
2716   ei->drop_delay_fixed = getFile8Bit(file);
2717   ei->push_delay_fixed = getFile8Bit(file);
2718   ei->drop_delay_random = getFile8Bit(file);
2719   ei->push_delay_random = getFile8Bit(file);
2720   ei->move_delay_fixed = getFile16BitBE(file);
2721   ei->move_delay_random = getFile16BitBE(file);
2722
2723   /* bits 0 - 15 of "move_pattern" ... */
2724   ei->move_pattern = getFile16BitBE(file);
2725   ei->move_direction_initial = getFile8Bit(file);
2726   ei->move_stepsize = getFile8Bit(file);
2727
2728   ei->slippery_type = getFile8Bit(file);
2729
2730   for (y = 0; y < 3; y++)
2731     for (x = 0; x < 3; x++)
2732       ei->content.e[x][y] = getMappedElement(getFile16BitBE(file));
2733
2734   ei->move_enter_element = getMappedElement(getFile16BitBE(file));
2735   ei->move_leave_element = getMappedElement(getFile16BitBE(file));
2736   ei->move_leave_type = getFile8Bit(file);
2737
2738   /* ... bits 16 - 31 of "move_pattern" (not nice, but downward compatible) */
2739   ei->move_pattern |= (getFile16BitBE(file) << 16);
2740
2741   ei->access_direction = getFile8Bit(file);
2742
2743   ei->explosion_delay = getFile8Bit(file);
2744   ei->ignition_delay = getFile8Bit(file);
2745   ei->explosion_type = getFile8Bit(file);
2746
2747   /* some free bytes for future custom property values and padding */
2748   ReadUnusedBytesFromFile(file, 1);
2749
2750   /* ---------- change page property values (48 bytes) --------------------- */
2751
2752   setElementChangePages(ei, ei->num_change_pages);
2753
2754   for (i = 0; i < ei->num_change_pages; i++)
2755   {
2756     struct ElementChangeInfo *change = &ei->change_page[i];
2757     unsigned int event_bits;
2758
2759     /* always start with reliable default values */
2760     setElementChangeInfoToDefaults(change);
2761
2762     /* bits 0 - 31 of "has_event[]" ... */
2763     event_bits = getFile32BitBE(file);
2764     for (j = 0; j < MIN(NUM_CHANGE_EVENTS, 32); j++)
2765       if (event_bits & (1 << j))
2766         change->has_event[j] = TRUE;
2767
2768     change->target_element = getMappedElement(getFile16BitBE(file));
2769
2770     change->delay_fixed = getFile16BitBE(file);
2771     change->delay_random = getFile16BitBE(file);
2772     change->delay_frames = getFile16BitBE(file);
2773
2774     change->initial_trigger_element = getMappedElement(getFile16BitBE(file));
2775
2776     change->explode = getFile8Bit(file);
2777     change->use_target_content = getFile8Bit(file);
2778     change->only_if_complete = getFile8Bit(file);
2779     change->use_random_replace = getFile8Bit(file);
2780
2781     change->random_percentage = getFile8Bit(file);
2782     change->replace_when = getFile8Bit(file);
2783
2784     for (y = 0; y < 3; y++)
2785       for (x = 0; x < 3; x++)
2786         change->target_content.e[x][y]= getMappedElement(getFile16BitBE(file));
2787
2788     change->can_change = getFile8Bit(file);
2789
2790     change->trigger_side = getFile8Bit(file);
2791
2792     change->trigger_player = getFile8Bit(file);
2793     change->trigger_page = getFile8Bit(file);
2794
2795     change->trigger_page = (change->trigger_page == CH_PAGE_ANY_FILE ?
2796                             CH_PAGE_ANY : (1 << change->trigger_page));
2797
2798     change->has_action = getFile8Bit(file);
2799     change->action_type = getFile8Bit(file);
2800     change->action_mode = getFile8Bit(file);
2801     change->action_arg = getFile16BitBE(file);
2802
2803     /* ... bits 32 - 39 of "has_event[]" (not nice, but downward compatible) */
2804     event_bits = getFile8Bit(file);
2805     for (j = 32; j < NUM_CHANGE_EVENTS; j++)
2806       if (event_bits & (1 << (j - 32)))
2807         change->has_event[j] = TRUE;
2808   }
2809
2810   /* mark this custom element as modified */
2811   ei->modified_settings = TRUE;
2812
2813   return chunk_size;
2814 }
2815
2816 static int LoadLevel_GRP1(File *file, int chunk_size, struct LevelInfo *level)
2817 {
2818   struct ElementInfo *ei;
2819   struct ElementGroupInfo *group;
2820   int element;
2821   int i;
2822
2823   element = getMappedElement(getFile16BitBE(file));
2824
2825   if (!IS_GROUP_ELEMENT(element))
2826   {
2827     Error(ERR_WARN, "invalid group element number %d", element);
2828
2829     ReadUnusedBytesFromFile(file, chunk_size - 2);
2830     return chunk_size;
2831   }
2832
2833   ei = &element_info[element];
2834
2835   for (i = 0; i < MAX_ELEMENT_NAME_LEN; i++)
2836     ei->description[i] = getFile8Bit(file);
2837   ei->description[MAX_ELEMENT_NAME_LEN] = 0;
2838
2839   group = element_info[element].group;
2840
2841   group->num_elements = getFile8Bit(file);
2842
2843   ei->use_gfx_element = getFile8Bit(file);
2844   ei->gfx_element_initial = getMappedElement(getFile16BitBE(file));
2845
2846   group->choice_mode = getFile8Bit(file);
2847
2848   /* some free bytes for future values and padding */
2849   ReadUnusedBytesFromFile(file, 3);
2850
2851   for (i = 0; i < MAX_ELEMENTS_IN_GROUP; i++)
2852     group->element[i] = getMappedElement(getFile16BitBE(file));
2853
2854   /* mark this group element as modified */
2855   element_info[element].modified_settings = TRUE;
2856
2857   return chunk_size;
2858 }
2859
2860 static int LoadLevel_MicroChunk(File *file, struct LevelFileConfigInfo *conf,
2861                                 int element, int real_element)
2862 {
2863   int micro_chunk_size = 0;
2864   int conf_type = getFile8Bit(file);
2865   int byte_mask = conf_type & CONF_MASK_BYTES;
2866   boolean element_found = FALSE;
2867   int i;
2868
2869   micro_chunk_size += 1;
2870
2871   if (byte_mask == CONF_MASK_MULTI_BYTES)
2872   {
2873     int num_bytes = getFile16BitBE(file);
2874     byte *buffer = checked_malloc(num_bytes);
2875
2876     ReadBytesFromFile(file, buffer, num_bytes);
2877
2878     for (i = 0; conf[i].data_type != -1; i++)
2879     {
2880       if (conf[i].element == element &&
2881           conf[i].conf_type == conf_type)
2882       {
2883         int data_type = conf[i].data_type;
2884         int num_entities = num_bytes / CONF_ENTITY_NUM_BYTES(data_type);
2885         int max_num_entities = conf[i].max_num_entities;
2886
2887         if (num_entities > max_num_entities)
2888         {
2889           Error(ERR_WARN,
2890                 "truncating number of entities for element %d from %d to %d",
2891                 element, num_entities, max_num_entities);
2892
2893           num_entities = max_num_entities;
2894         }
2895
2896         if (num_entities == 0 && (data_type == TYPE_ELEMENT_LIST ||
2897                                   data_type == TYPE_CONTENT_LIST))
2898         {
2899           /* for element and content lists, zero entities are not allowed */
2900           Error(ERR_WARN, "found empty list of entities for element %d",
2901                 element);
2902
2903           /* do not set "num_entities" here to prevent reading behind buffer */
2904
2905           *(int *)(conf[i].num_entities) = 1;   /* at least one is required */
2906         }
2907         else
2908         {
2909           *(int *)(conf[i].num_entities) = num_entities;
2910         }
2911
2912         element_found = TRUE;
2913
2914         if (data_type == TYPE_STRING)
2915         {
2916           char *string = (char *)(conf[i].value);
2917           int j;
2918
2919           for (j = 0; j < max_num_entities; j++)
2920             string[j] = (j < num_entities ? buffer[j] : '\0');
2921         }
2922         else if (data_type == TYPE_ELEMENT_LIST)
2923         {
2924           int *element_array = (int *)(conf[i].value);
2925           int j;
2926
2927           for (j = 0; j < num_entities; j++)
2928             element_array[j] =
2929               getMappedElement(CONF_ELEMENTS_ELEMENT(buffer, j));
2930         }
2931         else if (data_type == TYPE_CONTENT_LIST)
2932         {
2933           struct Content *content= (struct Content *)(conf[i].value);
2934           int c, x, y;
2935
2936           for (c = 0; c < num_entities; c++)
2937             for (y = 0; y < 3; y++)
2938               for (x = 0; x < 3; x++)
2939                 content[c].e[x][y] =
2940                   getMappedElement(CONF_CONTENTS_ELEMENT(buffer, c, x, y));
2941         }
2942         else
2943           element_found = FALSE;
2944
2945         break;
2946       }
2947     }
2948
2949     checked_free(buffer);
2950
2951     micro_chunk_size += 2 + num_bytes;
2952   }
2953   else          /* constant size configuration data (1, 2 or 4 bytes) */
2954   {
2955     int value = (byte_mask == CONF_MASK_1_BYTE ? getFile8Bit   (file) :
2956                  byte_mask == CONF_MASK_2_BYTE ? getFile16BitBE(file) :
2957                  byte_mask == CONF_MASK_4_BYTE ? getFile32BitBE(file) : 0);
2958
2959     for (i = 0; conf[i].data_type != -1; i++)
2960     {
2961       if (conf[i].element == element &&
2962           conf[i].conf_type == conf_type)
2963       {
2964         int data_type = conf[i].data_type;
2965
2966         if (data_type == TYPE_ELEMENT)
2967           value = getMappedElement(value);
2968
2969         if (data_type == TYPE_BOOLEAN)
2970           *(boolean *)(conf[i].value) = value;
2971         else
2972           *(int *)    (conf[i].value) = value;
2973
2974         element_found = TRUE;
2975
2976         break;
2977       }
2978     }
2979
2980     micro_chunk_size += CONF_VALUE_NUM_BYTES(byte_mask);
2981   }
2982
2983   if (!element_found)
2984   {
2985     char *error_conf_chunk_bytes =
2986       (byte_mask == CONF_MASK_1_BYTE ? "CONF_VALUE_8_BIT" :
2987        byte_mask == CONF_MASK_2_BYTE ? "CONF_VALUE_16_BIT" :
2988        byte_mask == CONF_MASK_4_BYTE ? "CONF_VALUE_32_BIT" :"CONF_VALUE_BYTES");
2989     int error_conf_chunk_token = conf_type & CONF_MASK_TOKEN;
2990     int error_element = real_element;
2991
2992     Error(ERR_WARN, "cannot load micro chunk '%s(%d)' value for element %d ['%s']",
2993           error_conf_chunk_bytes, error_conf_chunk_token,
2994           error_element, EL_NAME(error_element));
2995   }
2996
2997   return micro_chunk_size;
2998 }
2999
3000 static int LoadLevel_INFO(File *file, int chunk_size, struct LevelInfo *level)
3001 {
3002   int real_chunk_size = 0;
3003
3004   li = *level;          /* copy level data into temporary buffer */
3005
3006   while (!checkEndOfFile(file))
3007   {
3008     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_INFO, -1, -1);
3009
3010     if (real_chunk_size >= chunk_size)
3011       break;
3012   }
3013
3014   *level = li;          /* copy temporary buffer back to level data */
3015
3016   return real_chunk_size;
3017 }
3018
3019 static int LoadLevel_CONF(File *file, int chunk_size, struct LevelInfo *level)
3020 {
3021   int real_chunk_size = 0;
3022
3023   li = *level;          /* copy level data into temporary buffer */
3024
3025   while (!checkEndOfFile(file))
3026   {
3027     int element = getMappedElement(getFile16BitBE(file));
3028
3029     real_chunk_size += 2;
3030     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_CONF,
3031                                             element, element);
3032     if (real_chunk_size >= chunk_size)
3033       break;
3034   }
3035
3036   *level = li;          /* copy temporary buffer back to level data */
3037
3038   return real_chunk_size;
3039 }
3040
3041 static int LoadLevel_ELEM(File *file, int chunk_size, struct LevelInfo *level)
3042 {
3043   int real_chunk_size = 0;
3044
3045   li = *level;          /* copy level data into temporary buffer */
3046
3047   while (!checkEndOfFile(file))
3048   {
3049     int element = getMappedElement(getFile16BitBE(file));
3050
3051     real_chunk_size += 2;
3052     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_ELEM,
3053                                             element, element);
3054     if (real_chunk_size >= chunk_size)
3055       break;
3056   }
3057
3058   *level = li;          /* copy temporary buffer back to level data */
3059
3060   return real_chunk_size;
3061 }
3062
3063 static int LoadLevel_NOTE(File *file, int chunk_size, struct LevelInfo *level)
3064 {
3065   int element = getMappedElement(getFile16BitBE(file));
3066   int envelope_nr = element - EL_ENVELOPE_1;
3067   int real_chunk_size = 2;
3068
3069   xx_envelope = level->envelope[envelope_nr];   /* copy into temporary buffer */
3070
3071   while (!checkEndOfFile(file))
3072   {
3073     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_NOTE,
3074                                             -1, element);
3075
3076     if (real_chunk_size >= chunk_size)
3077       break;
3078   }
3079
3080   level->envelope[envelope_nr] = xx_envelope;   /* copy from temporary buffer */
3081
3082   return real_chunk_size;
3083 }
3084
3085 static int LoadLevel_CUSX(File *file, int chunk_size, struct LevelInfo *level)
3086 {
3087   int element = getMappedElement(getFile16BitBE(file));
3088   int real_chunk_size = 2;
3089   struct ElementInfo *ei = &element_info[element];
3090   int i;
3091
3092   xx_ei = *ei;          /* copy element data into temporary buffer */
3093
3094   xx_ei.num_change_pages = -1;
3095
3096   while (!checkEndOfFile(file))
3097   {
3098     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_CUSX_base,
3099                                             -1, element);
3100     if (xx_ei.num_change_pages != -1)
3101       break;
3102
3103     if (real_chunk_size >= chunk_size)
3104       break;
3105   }
3106
3107   *ei = xx_ei;
3108
3109   if (ei->num_change_pages == -1)
3110   {
3111     Error(ERR_WARN, "LoadLevel_CUSX(): missing 'num_change_pages' for '%s'",
3112           EL_NAME(element));
3113
3114     ei->num_change_pages = 1;
3115
3116     setElementChangePages(ei, 1);
3117     setElementChangeInfoToDefaults(ei->change);
3118
3119     return real_chunk_size;
3120   }
3121
3122   /* initialize number of change pages stored for this custom element */
3123   setElementChangePages(ei, ei->num_change_pages);
3124   for (i = 0; i < ei->num_change_pages; i++)
3125     setElementChangeInfoToDefaults(&ei->change_page[i]);
3126
3127   /* start with reading properties for the first change page */
3128   xx_current_change_page = 0;
3129
3130   while (!checkEndOfFile(file))
3131   {
3132     struct ElementChangeInfo *change = &ei->change_page[xx_current_change_page];
3133
3134     xx_change = *change;        /* copy change data into temporary buffer */
3135
3136     resetEventBits();           /* reset bits; change page might have changed */
3137
3138     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_CUSX_change,
3139                                             -1, element);
3140
3141     *change = xx_change;
3142
3143     setEventFlagsFromEventBits(change);
3144
3145     if (real_chunk_size >= chunk_size)
3146       break;
3147   }
3148
3149   return real_chunk_size;
3150 }
3151
3152 static int LoadLevel_GRPX(File *file, int chunk_size, struct LevelInfo *level)
3153 {
3154   int element = getMappedElement(getFile16BitBE(file));
3155   int real_chunk_size = 2;
3156   struct ElementInfo *ei = &element_info[element];
3157   struct ElementGroupInfo *group = ei->group;
3158
3159   xx_ei = *ei;          /* copy element data into temporary buffer */
3160   xx_group = *group;    /* copy group data into temporary buffer */
3161
3162   while (!checkEndOfFile(file))
3163   {
3164     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_GRPX,
3165                                             -1, element);
3166
3167     if (real_chunk_size >= chunk_size)
3168       break;
3169   }
3170
3171   *ei = xx_ei;
3172   *group = xx_group;
3173
3174   return real_chunk_size;
3175 }
3176
3177 static void LoadLevelFromFileInfo_RND(struct LevelInfo *level,
3178                                       struct LevelFileInfo *level_file_info,
3179                                       boolean level_info_only)
3180 {
3181   char *filename = level_file_info->filename;
3182   char cookie[MAX_LINE_LEN];
3183   char chunk_name[CHUNK_ID_LEN + 1];
3184   int chunk_size;
3185   File *file;
3186
3187   if (!(file = openFile(filename, MODE_READ)))
3188   {
3189     level->no_valid_file = TRUE;
3190     level->no_level_file = TRUE;
3191
3192     if (level_info_only)
3193       return;
3194
3195     Error(ERR_WARN, "cannot read level '%s' -- using empty level", filename);
3196
3197     if (!setup.editor.use_template_for_new_levels)
3198       return;
3199
3200     /* if level file not found, try to initialize level data from template */
3201     filename = getGlobalLevelTemplateFilename();
3202
3203     if (!(file = openFile(filename, MODE_READ)))
3204       return;
3205
3206     /* default: for empty levels, use level template for custom elements */
3207     level->use_custom_template = TRUE;
3208
3209     level->no_valid_file = FALSE;
3210   }
3211
3212   getFileChunkBE(file, chunk_name, NULL);
3213   if (strEqual(chunk_name, "RND1"))
3214   {
3215     getFile32BitBE(file);               /* not used */
3216
3217     getFileChunkBE(file, chunk_name, NULL);
3218     if (!strEqual(chunk_name, "CAVE"))
3219     {
3220       level->no_valid_file = TRUE;
3221
3222       Error(ERR_WARN, "unknown format of level file '%s'", filename);
3223
3224       closeFile(file);
3225
3226       return;
3227     }
3228   }
3229   else  /* check for pre-2.0 file format with cookie string */
3230   {
3231     strcpy(cookie, chunk_name);
3232     if (getStringFromFile(file, &cookie[4], MAX_LINE_LEN - 4) == NULL)
3233       cookie[4] = '\0';
3234     if (strlen(cookie) > 0 && cookie[strlen(cookie) - 1] == '\n')
3235       cookie[strlen(cookie) - 1] = '\0';
3236
3237     if (!checkCookieString(cookie, LEVEL_COOKIE_TMPL))
3238     {
3239       level->no_valid_file = TRUE;
3240
3241       Error(ERR_WARN, "unknown format of level file '%s'", filename);
3242
3243       closeFile(file);
3244
3245       return;
3246     }
3247
3248     if ((level->file_version = getFileVersionFromCookieString(cookie)) == -1)
3249     {
3250       level->no_valid_file = TRUE;
3251
3252       Error(ERR_WARN, "unsupported version of level file '%s'", filename);
3253
3254       closeFile(file);
3255
3256       return;
3257     }
3258
3259     /* pre-2.0 level files have no game version, so use file version here */
3260     level->game_version = level->file_version;
3261   }
3262
3263   if (level->file_version < FILE_VERSION_1_2)
3264   {
3265     /* level files from versions before 1.2.0 without chunk structure */
3266     LoadLevel_HEAD(file, LEVEL_CHUNK_HEAD_SIZE,         level);
3267     LoadLevel_BODY(file, level->fieldx * level->fieldy, level);
3268   }
3269   else
3270   {
3271     static struct
3272     {
3273       char *name;
3274       int size;
3275       int (*loader)(File *, int, struct LevelInfo *);
3276     }
3277     chunk_info[] =
3278     {
3279       { "VERS", LEVEL_CHUNK_VERS_SIZE,  LoadLevel_VERS },
3280       { "DATE", LEVEL_CHUNK_DATE_SIZE,  LoadLevel_DATE },
3281       { "HEAD", LEVEL_CHUNK_HEAD_SIZE,  LoadLevel_HEAD },
3282       { "NAME", LEVEL_CHUNK_NAME_SIZE,  LoadLevel_NAME },
3283       { "AUTH", LEVEL_CHUNK_AUTH_SIZE,  LoadLevel_AUTH },
3284       { "INFO", -1,                     LoadLevel_INFO },
3285       { "BODY", -1,                     LoadLevel_BODY },
3286       { "CONT", -1,                     LoadLevel_CONT },
3287       { "CNT2", LEVEL_CHUNK_CNT2_SIZE,  LoadLevel_CNT2 },
3288       { "CNT3", -1,                     LoadLevel_CNT3 },
3289       { "CUS1", -1,                     LoadLevel_CUS1 },
3290       { "CUS2", -1,                     LoadLevel_CUS2 },
3291       { "CUS3", -1,                     LoadLevel_CUS3 },
3292       { "CUS4", -1,                     LoadLevel_CUS4 },
3293       { "GRP1", -1,                     LoadLevel_GRP1 },
3294       { "CONF", -1,                     LoadLevel_CONF },
3295       { "ELEM", -1,                     LoadLevel_ELEM },
3296       { "NOTE", -1,                     LoadLevel_NOTE },
3297       { "CUSX", -1,                     LoadLevel_CUSX },
3298       { "GRPX", -1,                     LoadLevel_GRPX },
3299
3300       {  NULL,  0,                      NULL }
3301     };
3302
3303     while (getFileChunkBE(file, chunk_name, &chunk_size))
3304     {
3305       int i = 0;
3306
3307       while (chunk_info[i].name != NULL &&
3308              !strEqual(chunk_name, chunk_info[i].name))
3309         i++;
3310
3311       if (chunk_info[i].name == NULL)
3312       {
3313         Error(ERR_WARN, "unknown chunk '%s' in level file '%s'",
3314               chunk_name, filename);
3315         ReadUnusedBytesFromFile(file, chunk_size);
3316       }
3317       else if (chunk_info[i].size != -1 &&
3318                chunk_info[i].size != chunk_size)
3319       {
3320         Error(ERR_WARN, "wrong size (%d) of chunk '%s' in level file '%s'",
3321               chunk_size, chunk_name, filename);
3322         ReadUnusedBytesFromFile(file, chunk_size);
3323       }
3324       else
3325       {
3326         /* call function to load this level chunk */
3327         int chunk_size_expected =
3328           (chunk_info[i].loader)(file, chunk_size, level);
3329
3330         /* the size of some chunks cannot be checked before reading other
3331            chunks first (like "HEAD" and "BODY") that contain some header
3332            information, so check them here */
3333         if (chunk_size_expected != chunk_size)
3334         {
3335           Error(ERR_WARN, "wrong size (%d) of chunk '%s' in level file '%s'",
3336                 chunk_size, chunk_name, filename);
3337         }
3338       }
3339     }
3340   }
3341
3342   closeFile(file);
3343 }
3344
3345
3346 /* ------------------------------------------------------------------------- */
3347 /* functions for loading EM level                                            */
3348 /* ------------------------------------------------------------------------- */
3349
3350 void CopyNativeLevel_RND_to_EM(struct LevelInfo *level)
3351 {
3352   static int ball_xy[8][2] =
3353   {
3354     { 0, 0 },
3355     { 1, 0 },
3356     { 2, 0 },
3357     { 0, 1 },
3358     { 2, 1 },
3359     { 0, 2 },
3360     { 1, 2 },
3361     { 2, 2 },
3362   };
3363   struct LevelInfo_EM *level_em = level->native_em_level;
3364   struct LEVEL *lev = level_em->lev;
3365   struct PLAYER **ply = level_em->ply;
3366   int i, j, x, y;
3367
3368   lev->width  = MIN(level->fieldx, EM_MAX_CAVE_WIDTH);
3369   lev->height = MIN(level->fieldy, EM_MAX_CAVE_HEIGHT);
3370
3371   lev->time_seconds     = level->time;
3372   lev->required_initial = level->gems_needed;
3373
3374   lev->emerald_score    = level->score[SC_EMERALD];
3375   lev->diamond_score    = level->score[SC_DIAMOND];
3376   lev->alien_score      = level->score[SC_ROBOT];
3377   lev->tank_score       = level->score[SC_SPACESHIP];
3378   lev->bug_score        = level->score[SC_BUG];
3379   lev->eater_score      = level->score[SC_YAMYAM];
3380   lev->nut_score        = level->score[SC_NUT];
3381   lev->dynamite_score   = level->score[SC_DYNAMITE];
3382   lev->key_score        = level->score[SC_KEY];
3383   lev->exit_score       = level->score[SC_TIME_BONUS];
3384
3385   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
3386     for (y = 0; y < 3; y++)
3387       for (x = 0; x < 3; x++)
3388         lev->eater_array[i][y * 3 + x] =
3389           map_element_RND_to_EM(level->yamyam_content[i].e[x][y]);
3390
3391   lev->amoeba_time              = level->amoeba_speed;
3392   lev->wonderwall_time_initial  = level->time_magic_wall;
3393   lev->wheel_time               = level->time_wheel;
3394
3395   lev->android_move_time        = level->android_move_time;
3396   lev->android_clone_time       = level->android_clone_time;
3397   lev->ball_random              = level->ball_random;
3398   lev->ball_state_initial       = level->ball_state_initial;
3399   lev->ball_time                = level->ball_time;
3400   lev->num_ball_arrays          = level->num_ball_contents;
3401
3402   lev->lenses_score             = level->lenses_score;
3403   lev->magnify_score            = level->magnify_score;
3404   lev->slurp_score              = level->slurp_score;
3405
3406   lev->lenses_time              = level->lenses_time;
3407   lev->magnify_time             = level->magnify_time;
3408
3409   lev->wind_direction_initial =
3410     map_direction_RND_to_EM(level->wind_direction_initial);
3411   lev->wind_cnt_initial = (level->wind_direction_initial != MV_NONE ?
3412                            lev->wind_time : 0);
3413
3414   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
3415     for (j = 0; j < 8; j++)
3416       lev->ball_array[i][j] =
3417         map_element_RND_to_EM(level->
3418                               ball_content[i].e[ball_xy[j][0]][ball_xy[j][1]]);
3419
3420   map_android_clone_elements_RND_to_EM(level);
3421
3422   /* first fill the complete playfield with the default border element */
3423   for (y = 0; y < EM_MAX_CAVE_HEIGHT; y++)
3424     for (x = 0; x < EM_MAX_CAVE_WIDTH; x++)
3425       level_em->cave[x][y] = ZBORDER;
3426
3427   if (BorderElement == EL_STEELWALL)
3428   {
3429     for (y = 0; y < lev->height + 2; y++)
3430       for (x = 0; x < lev->width + 2; x++)
3431         level_em->cave[x + 1][y + 1] = map_element_RND_to_EM(EL_STEELWALL);
3432   }
3433
3434   /* then copy the real level contents from level file into the playfield */
3435   for (y = 0; y < lev->height; y++) for (x = 0; x < lev->width; x++)
3436   {
3437     int new_element = map_element_RND_to_EM(level->field[x][y]);
3438     int offset = (BorderElement == EL_STEELWALL ? 1 : 0);
3439     int xx = x + 1 + offset;
3440     int yy = y + 1 + offset;
3441
3442     if (level->field[x][y] == EL_AMOEBA_DEAD)
3443       new_element = map_element_RND_to_EM(EL_AMOEBA_WET);
3444
3445     level_em->cave[xx][yy] = new_element;
3446   }
3447
3448   for (i = 0; i < MAX_PLAYERS; i++)
3449   {
3450     ply[i]->x_initial = 0;
3451     ply[i]->y_initial = 0;
3452   }
3453
3454   /* initialize player positions and delete players from the playfield */
3455   for (y = 0; y < lev->height; y++) for (x = 0; x < lev->width; x++)
3456   {
3457     if (ELEM_IS_PLAYER(level->field[x][y]))
3458     {
3459       int player_nr = GET_PLAYER_NR(level->field[x][y]);
3460       int offset = (BorderElement == EL_STEELWALL ? 1 : 0);
3461       int xx = x + 1 + offset;
3462       int yy = y + 1 + offset;
3463
3464       ply[player_nr]->x_initial = xx;
3465       ply[player_nr]->y_initial = yy;
3466
3467       level_em->cave[xx][yy] = map_element_RND_to_EM(EL_EMPTY);
3468     }
3469   }
3470
3471   if (BorderElement == EL_STEELWALL)
3472   {
3473     lev->width  += 2;
3474     lev->height += 2;
3475   }
3476 }
3477
3478 void CopyNativeLevel_EM_to_RND(struct LevelInfo *level)
3479 {
3480   static int ball_xy[8][2] =
3481   {
3482     { 0, 0 },
3483     { 1, 0 },
3484     { 2, 0 },
3485     { 0, 1 },
3486     { 2, 1 },
3487     { 0, 2 },
3488     { 1, 2 },
3489     { 2, 2 },
3490   };
3491   struct LevelInfo_EM *level_em = level->native_em_level;
3492   struct LEVEL *lev = level_em->lev;
3493   struct PLAYER **ply = level_em->ply;
3494   int i, j, x, y;
3495
3496   level->fieldx = MIN(lev->width,  MAX_LEV_FIELDX);
3497   level->fieldy = MIN(lev->height, MAX_LEV_FIELDY);
3498
3499   level->time        = lev->time_seconds;
3500   level->gems_needed = lev->required_initial;
3501
3502   sprintf(level->name, "Level %d", level->file_info.nr);
3503
3504   level->score[SC_EMERALD]      = lev->emerald_score;
3505   level->score[SC_DIAMOND]      = lev->diamond_score;
3506   level->score[SC_ROBOT]        = lev->alien_score;
3507   level->score[SC_SPACESHIP]    = lev->tank_score;
3508   level->score[SC_BUG]          = lev->bug_score;
3509   level->score[SC_YAMYAM]       = lev->eater_score;
3510   level->score[SC_NUT]          = lev->nut_score;
3511   level->score[SC_DYNAMITE]     = lev->dynamite_score;
3512   level->score[SC_KEY]          = lev->key_score;
3513   level->score[SC_TIME_BONUS]   = lev->exit_score;
3514
3515   level->num_yamyam_contents = MAX_ELEMENT_CONTENTS;
3516
3517   for (i = 0; i < level->num_yamyam_contents; i++)
3518     for (y = 0; y < 3; y++)
3519       for (x = 0; x < 3; x++)
3520         level->yamyam_content[i].e[x][y] =
3521           map_element_EM_to_RND(lev->eater_array[i][y * 3 + x]);
3522
3523   level->amoeba_speed           = lev->amoeba_time;
3524   level->time_magic_wall        = lev->wonderwall_time_initial;
3525   level->time_wheel             = lev->wheel_time;
3526
3527   level->android_move_time      = lev->android_move_time;
3528   level->android_clone_time     = lev->android_clone_time;
3529   level->ball_random            = lev->ball_random;
3530   level->ball_state_initial     = lev->ball_state_initial;
3531   level->ball_time              = lev->ball_time;
3532   level->num_ball_contents      = lev->num_ball_arrays;
3533
3534   level->lenses_score           = lev->lenses_score;
3535   level->magnify_score          = lev->magnify_score;
3536   level->slurp_score            = lev->slurp_score;
3537
3538   level->lenses_time            = lev->lenses_time;
3539   level->magnify_time           = lev->magnify_time;
3540
3541   level->wind_direction_initial =
3542     map_direction_EM_to_RND(lev->wind_direction_initial);
3543
3544   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
3545     for (j = 0; j < 8; j++)
3546       level->ball_content[i].e[ball_xy[j][0]][ball_xy[j][1]] =
3547         map_element_EM_to_RND(lev->ball_array[i][j]);
3548
3549   map_android_clone_elements_EM_to_RND(level);
3550
3551   /* convert the playfield (some elements need special treatment) */
3552   for (y = 0; y < level->fieldy; y++) for (x = 0; x < level->fieldx; x++)
3553   {
3554     int new_element = map_element_EM_to_RND(level_em->cave[x + 1][y + 1]);
3555
3556     if (new_element == EL_AMOEBA_WET && level->amoeba_speed == 0)
3557       new_element = EL_AMOEBA_DEAD;
3558
3559     level->field[x][y] = new_element;
3560   }
3561
3562   for (i = 0; i < MAX_PLAYERS; i++)
3563   {
3564     /* in case of all players set to the same field, use the first player */
3565     int nr = MAX_PLAYERS - i - 1;
3566     int jx = ply[nr]->x_initial - 1;
3567     int jy = ply[nr]->y_initial - 1;
3568
3569     if (jx != -1 && jy != -1)
3570       level->field[jx][jy] = EL_PLAYER_1 + nr;
3571   }
3572 }
3573
3574
3575 /* ------------------------------------------------------------------------- */
3576 /* functions for loading SP level                                            */
3577 /* ------------------------------------------------------------------------- */
3578
3579 void CopyNativeLevel_RND_to_SP(struct LevelInfo *level)
3580 {
3581   struct LevelInfo_SP *level_sp = level->native_sp_level;
3582   LevelInfoType *header = &level_sp->header;
3583   int i, x, y;
3584
3585   level_sp->width  = level->fieldx;
3586   level_sp->height = level->fieldy;
3587
3588   for (x = 0; x < level->fieldx; x++)
3589     for (y = 0; y < level->fieldy; y++)
3590       level_sp->playfield[x][y] = map_element_RND_to_SP(level->field[x][y]);
3591
3592   header->InitialGravity = (level->initial_player_gravity[0] ? 1 : 0);
3593
3594   for (i = 0; i < SP_LEVEL_NAME_LEN; i++)
3595     header->LevelTitle[i] = level->name[i];
3596   /* !!! NO STRING TERMINATION IN SUPAPLEX VB CODE YET -- FIX THIS !!! */
3597
3598   header->InfotronsNeeded = level->gems_needed;
3599
3600   header->SpecialPortCount = 0;
3601
3602   for (x = 0; x < level->fieldx; x++) for (y = 0; y < level->fieldy; y++)
3603   {
3604     boolean gravity_port_found = FALSE;
3605     boolean gravity_port_valid = FALSE;
3606     int gravity_port_flag;
3607     int gravity_port_base_element;
3608     int element = level->field[x][y];
3609
3610     if (element >= EL_SP_GRAVITY_ON_PORT_RIGHT &&
3611         element <= EL_SP_GRAVITY_ON_PORT_UP)
3612     {
3613       gravity_port_found = TRUE;
3614       gravity_port_valid = TRUE;
3615       gravity_port_flag = 1;
3616       gravity_port_base_element = EL_SP_GRAVITY_ON_PORT_RIGHT;
3617     }
3618     else if (element >= EL_SP_GRAVITY_OFF_PORT_RIGHT &&
3619              element <= EL_SP_GRAVITY_OFF_PORT_UP)
3620     {
3621       gravity_port_found = TRUE;
3622       gravity_port_valid = TRUE;
3623       gravity_port_flag = 0;
3624       gravity_port_base_element = EL_SP_GRAVITY_OFF_PORT_RIGHT;
3625     }
3626     else if (element >= EL_SP_GRAVITY_PORT_RIGHT &&
3627              element <= EL_SP_GRAVITY_PORT_UP)
3628     {
3629       /* change R'n'D style gravity inverting special port to normal port
3630          (there are no gravity inverting ports in native Supaplex engine) */
3631
3632       gravity_port_found = TRUE;
3633       gravity_port_valid = FALSE;
3634       gravity_port_base_element = EL_SP_GRAVITY_PORT_RIGHT;
3635     }
3636
3637     if (gravity_port_found)
3638     {
3639       if (gravity_port_valid &&
3640           header->SpecialPortCount < SP_MAX_SPECIAL_PORTS)
3641       {
3642         SpecialPortType *port = &header->SpecialPort[header->SpecialPortCount];
3643
3644         port->PortLocation = (y * level->fieldx + x) * 2;
3645         port->Gravity = gravity_port_flag;
3646
3647         element += EL_SP_GRAVITY_PORT_RIGHT - gravity_port_base_element;
3648
3649         header->SpecialPortCount++;
3650       }
3651       else
3652       {
3653         /* change special gravity port to normal port */
3654
3655         element += EL_SP_PORT_RIGHT - gravity_port_base_element;
3656       }
3657
3658       level_sp->playfield[x][y] = element - EL_SP_START;
3659     }
3660   }
3661 }
3662
3663 void CopyNativeLevel_SP_to_RND(struct LevelInfo *level)
3664 {
3665   struct LevelInfo_SP *level_sp = level->native_sp_level;
3666   LevelInfoType *header = &level_sp->header;
3667   int i, x, y;
3668
3669   level->fieldx = level_sp->width;
3670   level->fieldy = level_sp->height;
3671
3672   for (x = 0; x < level->fieldx; x++)
3673   {
3674     for (y = 0; y < level->fieldy; y++)
3675     {
3676       int element_old = level_sp->playfield[x][y];
3677       int element_new = getMappedElement(map_element_SP_to_RND(element_old));
3678
3679       if (element_new == EL_UNKNOWN)
3680         Error(ERR_WARN, "invalid element %d at position %d, %d",
3681               element_old, x, y);
3682
3683       level->field[x][y] = element_new;
3684     }
3685   }
3686
3687   for (i = 0; i < MAX_PLAYERS; i++)
3688     level->initial_player_gravity[i] =
3689       (header->InitialGravity == 1 ? TRUE : FALSE);
3690
3691   for (i = 0; i < SP_LEVEL_NAME_LEN; i++)
3692     level->name[i] = header->LevelTitle[i];
3693   level->name[SP_LEVEL_NAME_LEN] = '\0';
3694
3695   level->gems_needed = header->InfotronsNeeded;
3696
3697   for (i = 0; i < header->SpecialPortCount; i++)
3698   {
3699     SpecialPortType *port = &header->SpecialPort[i];
3700     int port_location = port->PortLocation;
3701     int gravity = port->Gravity;
3702     int port_x, port_y, port_element;
3703
3704     port_x = (port_location / 2) % level->fieldx;
3705     port_y = (port_location / 2) / level->fieldx;
3706
3707     if (port_x < 0 || port_x >= level->fieldx ||
3708         port_y < 0 || port_y >= level->fieldy)
3709     {
3710       Error(ERR_WARN, "special port position (%d, %d) out of bounds",
3711             port_x, port_y);
3712
3713       continue;
3714     }
3715
3716     port_element = level->field[port_x][port_y];
3717
3718     if (port_element < EL_SP_GRAVITY_PORT_RIGHT ||
3719         port_element > EL_SP_GRAVITY_PORT_UP)
3720     {
3721       Error(ERR_WARN, "no special port at position (%d, %d)", port_x, port_y);
3722
3723       continue;
3724     }
3725
3726     /* change previous (wrong) gravity inverting special port to either
3727        gravity enabling special port or gravity disabling special port */
3728     level->field[port_x][port_y] +=