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