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