moved setting auto-exit for Sokoban-style levels from runtime to level
[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 //                  https://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  1       // unused tape header bytes
62 #define TAPE_CHUNK_SCRN_SIZE    2       // size of screen size chunk
63
64 #define SCORE_CHUNK_VERS_SIZE   8       // size of file version chunk
65
66 #define LEVEL_CHUNK_CNT3_SIZE(x)         (LEVEL_CHUNK_CNT3_HEADER + (x))
67 #define LEVEL_CHUNK_CUS3_SIZE(x)         (2 + (x) * LEVEL_CPART_CUS3_SIZE)
68 #define LEVEL_CHUNK_CUS4_SIZE(x)         (96 + (x) * 48)
69
70 // file identifier strings
71 #define LEVEL_COOKIE_TMPL               "ROCKSNDIAMONDS_LEVEL_FILE_VERSION_x.x"
72 #define TAPE_COOKIE_TMPL                "ROCKSNDIAMONDS_TAPE_FILE_VERSION_x.x"
73 #define SCORE_COOKIE_TMPL               "ROCKSNDIAMONDS_SCORE_FILE_VERSION_x.x"
74
75 // values for deciding when (not) to save configuration data
76 #define SAVE_CONF_NEVER                 0
77 #define SAVE_CONF_ALWAYS                1
78 #define SAVE_CONF_WHEN_CHANGED          -1
79
80 // values for chunks using micro chunks
81 #define CONF_MASK_1_BYTE                0x00
82 #define CONF_MASK_2_BYTE                0x40
83 #define CONF_MASK_4_BYTE                0x80
84 #define CONF_MASK_MULTI_BYTES           0xc0
85
86 #define CONF_MASK_BYTES                 0xc0
87 #define CONF_MASK_TOKEN                 0x3f
88
89 #define CONF_VALUE_1_BYTE(x)            (CONF_MASK_1_BYTE       | (x))
90 #define CONF_VALUE_2_BYTE(x)            (CONF_MASK_2_BYTE       | (x))
91 #define CONF_VALUE_4_BYTE(x)            (CONF_MASK_4_BYTE       | (x))
92 #define CONF_VALUE_MULTI_BYTES(x)       (CONF_MASK_MULTI_BYTES  | (x))
93
94 // these definitions are just for convenience of use and readability
95 #define CONF_VALUE_8_BIT(x)             CONF_VALUE_1_BYTE(x)
96 #define CONF_VALUE_16_BIT(x)            CONF_VALUE_2_BYTE(x)
97 #define CONF_VALUE_32_BIT(x)            CONF_VALUE_4_BYTE(x)
98 #define CONF_VALUE_BYTES(x)             CONF_VALUE_MULTI_BYTES(x)
99
100 #define CONF_VALUE_NUM_BYTES(x)         ((x) == CONF_MASK_1_BYTE ? 1 :  \
101                                          (x) == CONF_MASK_2_BYTE ? 2 :  \
102                                          (x) == CONF_MASK_4_BYTE ? 4 : 0)
103
104 #define CONF_CONTENT_NUM_ELEMENTS       (3 * 3)
105 #define CONF_CONTENT_NUM_BYTES          (CONF_CONTENT_NUM_ELEMENTS * 2)
106 #define CONF_ELEMENT_NUM_BYTES          (2)
107
108 #define CONF_ENTITY_NUM_BYTES(t)        ((t) == TYPE_ELEMENT ||         \
109                                          (t) == TYPE_ELEMENT_LIST ?     \
110                                          CONF_ELEMENT_NUM_BYTES :       \
111                                          (t) == TYPE_CONTENT ||         \
112                                          (t) == TYPE_CONTENT_LIST ?     \
113                                          CONF_CONTENT_NUM_BYTES : 1)
114
115 #define CONF_ELEMENT_BYTE_POS(i)        ((i) * CONF_ELEMENT_NUM_BYTES)
116 #define CONF_ELEMENTS_ELEMENT(b,i)     ((b[CONF_ELEMENT_BYTE_POS(i)] << 8) |  \
117                                         (b[CONF_ELEMENT_BYTE_POS(i) + 1]))
118
119 #define CONF_CONTENT_ELEMENT_POS(c,x,y) ((c) * CONF_CONTENT_NUM_ELEMENTS +    \
120                                          (y) * 3 + (x))
121 #define CONF_CONTENT_BYTE_POS(c,x,y)    (CONF_CONTENT_ELEMENT_POS(c,x,y) *    \
122                                          CONF_ELEMENT_NUM_BYTES)
123 #define CONF_CONTENTS_ELEMENT(b,c,x,y) ((b[CONF_CONTENT_BYTE_POS(c,x,y)]<< 8)|\
124                                         (b[CONF_CONTENT_BYTE_POS(c,x,y) + 1]))
125
126 // temporary variables used to store pointers to structure members
127 static struct LevelInfo li;
128 static struct ElementInfo xx_ei, yy_ei;
129 static struct ElementChangeInfo xx_change;
130 static struct ElementGroupInfo xx_group;
131 static struct EnvelopeInfo xx_envelope;
132 static unsigned int xx_event_bits[NUM_CE_BITFIELDS];
133 static char xx_default_description[MAX_ELEMENT_NAME_LEN + 1];
134 static int xx_num_contents;
135 static int xx_current_change_page;
136 static char xx_default_string_empty[1] = "";
137 static int xx_string_length_unused;
138
139 struct LevelFileConfigInfo
140 {
141   int element;                  // element for which data is to be stored
142   int save_type;                // save data always, never or when changed
143   int data_type;                // data type (used internally, not stored)
144   int conf_type;                // micro chunk identifier (stored in file)
145
146   // (mandatory)
147   void *value;                  // variable that holds the data to be stored
148   int default_value;            // initial default value for this variable
149
150   // (optional)
151   void *value_copy;             // variable that holds the data to be copied
152   void *num_entities;           // number of entities for multi-byte data
153   int default_num_entities;     // default number of entities for this data
154   int max_num_entities;         // maximal number of entities for this data
155   char *default_string;         // optional default string for string data
156 };
157
158 static struct LevelFileConfigInfo chunk_config_INFO[] =
159 {
160   // ---------- values not related to single elements -------------------------
161
162   {
163     -1,                                 SAVE_CONF_ALWAYS,
164     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
165     &li.game_engine_type,               GAME_ENGINE_TYPE_RND
166   },
167
168   {
169     -1,                                 SAVE_CONF_ALWAYS,
170     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
171     &li.fieldx,                         STD_LEV_FIELDX
172   },
173   {
174     -1,                                 SAVE_CONF_ALWAYS,
175     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
176     &li.fieldy,                         STD_LEV_FIELDY
177   },
178
179   {
180     -1,                                 SAVE_CONF_ALWAYS,
181     TYPE_INTEGER,                       CONF_VALUE_16_BIT(3),
182     &li.time,                           100
183   },
184
185   {
186     -1,                                 SAVE_CONF_ALWAYS,
187     TYPE_INTEGER,                       CONF_VALUE_16_BIT(4),
188     &li.gems_needed,                    0
189   },
190
191   {
192     -1,                                 -1,
193     TYPE_INTEGER,                       CONF_VALUE_32_BIT(2),
194     &li.random_seed,                    0
195   },
196
197   {
198     -1,                                 -1,
199     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(2),
200     &li.use_step_counter,               FALSE
201   },
202
203   {
204     -1,                                 -1,
205     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(4),
206     &li.wind_direction_initial,         MV_NONE
207   },
208
209   {
210     -1,                                 -1,
211     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(5),
212     &li.em_slippery_gems,               FALSE
213   },
214
215   {
216     -1,                                 -1,
217     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(6),
218     &li.use_custom_template,            FALSE
219   },
220
221   {
222     -1,                                 -1,
223     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(1),
224     &li.can_move_into_acid_bits,        ~0      // default: everything can
225   },
226
227   {
228     -1,                                 -1,
229     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(7),
230     &li.dont_collide_with_bits,         ~0      // default: always deadly
231   },
232
233   {
234     -1,                                 -1,
235     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
236     &li.em_explodes_by_fire,            FALSE
237   },
238
239   {
240     -1,                                 -1,
241     TYPE_INTEGER,                       CONF_VALUE_16_BIT(5),
242     &li.score[SC_TIME_BONUS],           1
243   },
244
245   {
246     -1,                                 -1,
247     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
248     &li.auto_exit_sokoban,              FALSE
249   },
250
251   {
252     -1,                                 -1,
253     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
254     &li.auto_count_gems,                FALSE
255   },
256
257   {
258     -1,                                 -1,
259     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
260     &li.solved_by_one_player,           FALSE
261   },
262
263   {
264     -1,                                 -1,
265     TYPE_INTEGER,                       CONF_VALUE_8_BIT(12),
266     &li.time_score_base,                1
267   },
268
269   {
270     -1,                                 -1,
271     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
272     &li.rate_time_over_score,           FALSE
273   },
274
275   {
276     -1,                                 -1,
277     -1,                                 -1,
278     NULL,                               -1
279   }
280 };
281
282 static struct LevelFileConfigInfo chunk_config_ELEM[] =
283 {
284   // (these values are the same for each player)
285   {
286     EL_PLAYER_1,                        -1,
287     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
288     &li.block_last_field,               FALSE   // default case for EM levels
289   },
290   {
291     EL_PLAYER_1,                        -1,
292     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(2),
293     &li.sp_block_last_field,            TRUE    // default case for SP levels
294   },
295   {
296     EL_PLAYER_1,                        -1,
297     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(3),
298     &li.instant_relocation,             FALSE
299   },
300   {
301     EL_PLAYER_1,                        -1,
302     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(4),
303     &li.can_pass_to_walkable,           FALSE
304   },
305   {
306     EL_PLAYER_1,                        -1,
307     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(5),
308     &li.block_snap_field,               TRUE
309   },
310   {
311     EL_PLAYER_1,                        -1,
312     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(6),
313     &li.continuous_snapping,            TRUE
314   },
315   {
316     EL_PLAYER_1,                        -1,
317     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(12),
318     &li.shifted_relocation,             FALSE
319   },
320   {
321     EL_PLAYER_1,                        -1,
322     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(15),
323     &li.lazy_relocation,                FALSE
324   },
325   {
326     EL_PLAYER_1,                        -1,
327     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(16),
328     &li.finish_dig_collect,             TRUE
329   },
330   {
331     EL_PLAYER_1,                        -1,
332     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(17),
333     &li.keep_walkable_ce,               FALSE
334   },
335
336   // (these values are different for each player)
337   {
338     EL_PLAYER_1,                        -1,
339     TYPE_INTEGER,                       CONF_VALUE_8_BIT(7),
340     &li.initial_player_stepsize[0],     STEPSIZE_NORMAL
341   },
342   {
343     EL_PLAYER_1,                        -1,
344     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
345     &li.initial_player_gravity[0],      FALSE
346   },
347   {
348     EL_PLAYER_1,                        -1,
349     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
350     &li.use_start_element[0],           FALSE
351   },
352   {
353     EL_PLAYER_1,                        -1,
354     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
355     &li.start_element[0],               EL_PLAYER_1
356   },
357   {
358     EL_PLAYER_1,                        -1,
359     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
360     &li.use_artwork_element[0],         FALSE
361   },
362   {
363     EL_PLAYER_1,                        -1,
364     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(2),
365     &li.artwork_element[0],             EL_PLAYER_1
366   },
367   {
368     EL_PLAYER_1,                        -1,
369     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
370     &li.use_explosion_element[0],       FALSE
371   },
372   {
373     EL_PLAYER_1,                        -1,
374     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(3),
375     &li.explosion_element[0],           EL_PLAYER_1
376   },
377   {
378     EL_PLAYER_1,                        -1,
379     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
380     &li.use_initial_inventory[0],       FALSE
381   },
382   {
383     EL_PLAYER_1,                        -1,
384     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(14),
385     &li.initial_inventory_size[0],      1
386   },
387   {
388     EL_PLAYER_1,                        -1,
389     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(1),
390     &li.initial_inventory_content[0][0],EL_EMPTY, NULL,
391     &li.initial_inventory_size[0],      1, MAX_INITIAL_INVENTORY_SIZE
392   },
393
394   {
395     EL_PLAYER_2,                        -1,
396     TYPE_INTEGER,                       CONF_VALUE_8_BIT(7),
397     &li.initial_player_stepsize[1],     STEPSIZE_NORMAL
398   },
399   {
400     EL_PLAYER_2,                        -1,
401     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
402     &li.initial_player_gravity[1],      FALSE
403   },
404   {
405     EL_PLAYER_2,                        -1,
406     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
407     &li.use_start_element[1],           FALSE
408   },
409   {
410     EL_PLAYER_2,                        -1,
411     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
412     &li.start_element[1],               EL_PLAYER_2
413   },
414   {
415     EL_PLAYER_2,                        -1,
416     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
417     &li.use_artwork_element[1],         FALSE
418   },
419   {
420     EL_PLAYER_2,                        -1,
421     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(2),
422     &li.artwork_element[1],             EL_PLAYER_2
423   },
424   {
425     EL_PLAYER_2,                        -1,
426     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
427     &li.use_explosion_element[1],       FALSE
428   },
429   {
430     EL_PLAYER_2,                        -1,
431     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(3),
432     &li.explosion_element[1],           EL_PLAYER_2
433   },
434   {
435     EL_PLAYER_2,                        -1,
436     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
437     &li.use_initial_inventory[1],       FALSE
438   },
439   {
440     EL_PLAYER_2,                        -1,
441     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(14),
442     &li.initial_inventory_size[1],      1
443   },
444   {
445     EL_PLAYER_2,                        -1,
446     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(1),
447     &li.initial_inventory_content[1][0],EL_EMPTY, NULL,
448     &li.initial_inventory_size[1],      1, MAX_INITIAL_INVENTORY_SIZE
449   },
450
451   {
452     EL_PLAYER_3,                        -1,
453     TYPE_INTEGER,                       CONF_VALUE_8_BIT(7),
454     &li.initial_player_stepsize[2],     STEPSIZE_NORMAL
455   },
456   {
457     EL_PLAYER_3,                        -1,
458     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
459     &li.initial_player_gravity[2],      FALSE
460   },
461   {
462     EL_PLAYER_3,                        -1,
463     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
464     &li.use_start_element[2],           FALSE
465   },
466   {
467     EL_PLAYER_3,                        -1,
468     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
469     &li.start_element[2],               EL_PLAYER_3
470   },
471   {
472     EL_PLAYER_3,                        -1,
473     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
474     &li.use_artwork_element[2],         FALSE
475   },
476   {
477     EL_PLAYER_3,                        -1,
478     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(2),
479     &li.artwork_element[2],             EL_PLAYER_3
480   },
481   {
482     EL_PLAYER_3,                        -1,
483     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
484     &li.use_explosion_element[2],       FALSE
485   },
486   {
487     EL_PLAYER_3,                        -1,
488     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(3),
489     &li.explosion_element[2],           EL_PLAYER_3
490   },
491   {
492     EL_PLAYER_3,                        -1,
493     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
494     &li.use_initial_inventory[2],       FALSE
495   },
496   {
497     EL_PLAYER_3,                        -1,
498     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(14),
499     &li.initial_inventory_size[2],      1
500   },
501   {
502     EL_PLAYER_3,                        -1,
503     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(1),
504     &li.initial_inventory_content[2][0],EL_EMPTY, NULL,
505     &li.initial_inventory_size[2],      1, MAX_INITIAL_INVENTORY_SIZE
506   },
507
508   {
509     EL_PLAYER_4,                        -1,
510     TYPE_INTEGER,                       CONF_VALUE_8_BIT(7),
511     &li.initial_player_stepsize[3],     STEPSIZE_NORMAL
512   },
513   {
514     EL_PLAYER_4,                        -1,
515     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
516     &li.initial_player_gravity[3],      FALSE
517   },
518   {
519     EL_PLAYER_4,                        -1,
520     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
521     &li.use_start_element[3],           FALSE
522   },
523   {
524     EL_PLAYER_4,                        -1,
525     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
526     &li.start_element[3],               EL_PLAYER_4
527   },
528   {
529     EL_PLAYER_4,                        -1,
530     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
531     &li.use_artwork_element[3],         FALSE
532   },
533   {
534     EL_PLAYER_4,                        -1,
535     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(2),
536     &li.artwork_element[3],             EL_PLAYER_4
537   },
538   {
539     EL_PLAYER_4,                        -1,
540     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
541     &li.use_explosion_element[3],       FALSE
542   },
543   {
544     EL_PLAYER_4,                        -1,
545     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(3),
546     &li.explosion_element[3],           EL_PLAYER_4
547   },
548   {
549     EL_PLAYER_4,                        -1,
550     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
551     &li.use_initial_inventory[3],       FALSE
552   },
553   {
554     EL_PLAYER_4,                        -1,
555     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(14),
556     &li.initial_inventory_size[3],      1
557   },
558   {
559     EL_PLAYER_4,                        -1,
560     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(1),
561     &li.initial_inventory_content[3][0],EL_EMPTY, NULL,
562     &li.initial_inventory_size[3],      1, MAX_INITIAL_INVENTORY_SIZE
563   },
564
565   {
566     EL_EMERALD,                         -1,
567     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
568     &li.score[SC_EMERALD],              10
569   },
570
571   {
572     EL_DIAMOND,                         -1,
573     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
574     &li.score[SC_DIAMOND],              10
575   },
576
577   {
578     EL_BUG,                             -1,
579     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
580     &li.score[SC_BUG],                  10
581   },
582
583   {
584     EL_SPACESHIP,                       -1,
585     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
586     &li.score[SC_SPACESHIP],            10
587   },
588
589   {
590     EL_PACMAN,                          -1,
591     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
592     &li.score[SC_PACMAN],               10
593   },
594
595   {
596     EL_NUT,                             -1,
597     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
598     &li.score[SC_NUT],                  10
599   },
600
601   {
602     EL_DYNAMITE,                        -1,
603     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
604     &li.score[SC_DYNAMITE],             10
605   },
606
607   {
608     EL_KEY_1,                           -1,
609     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
610     &li.score[SC_KEY],                  10
611   },
612
613   {
614     EL_PEARL,                           -1,
615     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
616     &li.score[SC_PEARL],                10
617   },
618
619   {
620     EL_CRYSTAL,                         -1,
621     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
622     &li.score[SC_CRYSTAL],              10
623   },
624
625   {
626     EL_BD_AMOEBA,                       -1,
627     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
628     &li.amoeba_content,                 EL_DIAMOND
629   },
630   {
631     EL_BD_AMOEBA,                       -1,
632     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
633     &li.amoeba_speed,                   10
634   },
635   {
636     EL_BD_AMOEBA,                       -1,
637     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
638     &li.grow_into_diggable,             TRUE
639   },
640
641   {
642     EL_YAMYAM,                          -1,
643     TYPE_CONTENT_LIST,                  CONF_VALUE_BYTES(1),
644     &li.yamyam_content,                 EL_ROCK, NULL,
645     &li.num_yamyam_contents,            4, MAX_ELEMENT_CONTENTS
646   },
647   {
648     EL_YAMYAM,                          -1,
649     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
650     &li.score[SC_YAMYAM],               10
651   },
652
653   {
654     EL_ROBOT,                           -1,
655     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
656     &li.score[SC_ROBOT],                10
657   },
658   {
659     EL_ROBOT,                           -1,
660     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
661     &li.slurp_score,                    10
662   },
663
664   {
665     EL_ROBOT_WHEEL,                     -1,
666     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
667     &li.time_wheel,                     10
668   },
669
670   {
671     EL_MAGIC_WALL,                      -1,
672     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
673     &li.time_magic_wall,                10
674   },
675
676   {
677     EL_GAME_OF_LIFE,                    -1,
678     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
679     &li.game_of_life[0],                2
680   },
681   {
682     EL_GAME_OF_LIFE,                    -1,
683     TYPE_INTEGER,                       CONF_VALUE_8_BIT(2),
684     &li.game_of_life[1],                3
685   },
686   {
687     EL_GAME_OF_LIFE,                    -1,
688     TYPE_INTEGER,                       CONF_VALUE_8_BIT(3),
689     &li.game_of_life[2],                3
690   },
691   {
692     EL_GAME_OF_LIFE,                    -1,
693     TYPE_INTEGER,                       CONF_VALUE_8_BIT(4),
694     &li.game_of_life[3],                3
695   },
696   {
697     EL_GAME_OF_LIFE,                    -1,
698     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(5),
699     &li.use_life_bugs,                  FALSE
700   },
701
702   {
703     EL_BIOMAZE,                         -1,
704     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
705     &li.biomaze[0],                     2
706   },
707   {
708     EL_BIOMAZE,                         -1,
709     TYPE_INTEGER,                       CONF_VALUE_8_BIT(2),
710     &li.biomaze[1],                     3
711   },
712   {
713     EL_BIOMAZE,                         -1,
714     TYPE_INTEGER,                       CONF_VALUE_8_BIT(3),
715     &li.biomaze[2],                     3
716   },
717   {
718     EL_BIOMAZE,                         -1,
719     TYPE_INTEGER,                       CONF_VALUE_8_BIT(4),
720     &li.biomaze[3],                     3
721   },
722
723   {
724     EL_TIMEGATE_SWITCH,                 -1,
725     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
726     &li.time_timegate,                  10
727   },
728
729   {
730     EL_LIGHT_SWITCH_ACTIVE,             -1,
731     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
732     &li.time_light,                     10
733   },
734
735   {
736     EL_SHIELD_NORMAL,                   -1,
737     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
738     &li.shield_normal_time,             10
739   },
740   {
741     EL_SHIELD_NORMAL,                   -1,
742     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
743     &li.score[SC_SHIELD],               10
744   },
745
746   {
747     EL_SHIELD_DEADLY,                   -1,
748     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
749     &li.shield_deadly_time,             10
750   },
751   {
752     EL_SHIELD_DEADLY,                   -1,
753     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
754     &li.score[SC_SHIELD],               10
755   },
756
757   {
758     EL_EXTRA_TIME,                      -1,
759     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
760     &li.extra_time,                     10
761   },
762   {
763     EL_EXTRA_TIME,                      -1,
764     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
765     &li.extra_time_score,               10
766   },
767
768   {
769     EL_TIME_ORB_FULL,                   -1,
770     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
771     &li.time_orb_time,                  10
772   },
773   {
774     EL_TIME_ORB_FULL,                   -1,
775     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
776     &li.use_time_orb_bug,               FALSE
777   },
778
779   {
780     EL_SPRING,                          -1,
781     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
782     &li.use_spring_bug,                 FALSE
783   },
784
785   {
786     EL_EMC_ANDROID,                     -1,
787     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
788     &li.android_move_time,              10
789   },
790   {
791     EL_EMC_ANDROID,                     -1,
792     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
793     &li.android_clone_time,             10
794   },
795   {
796     EL_EMC_ANDROID,                     SAVE_CONF_NEVER,
797     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(1),
798     &li.android_clone_element[0],       EL_EMPTY, NULL,
799     &li.num_android_clone_elements,     1, MAX_ANDROID_ELEMENTS_OLD
800   },
801   {
802     EL_EMC_ANDROID,                     -1,
803     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(2),
804     &li.android_clone_element[0],       EL_EMPTY, NULL,
805     &li.num_android_clone_elements,     1, MAX_ANDROID_ELEMENTS
806   },
807
808   {
809     EL_EMC_LENSES,                      -1,
810     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
811     &li.lenses_score,                   10
812   },
813   {
814     EL_EMC_LENSES,                      -1,
815     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
816     &li.lenses_time,                    10
817   },
818
819   {
820     EL_EMC_MAGNIFIER,                   -1,
821     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
822     &li.magnify_score,                  10
823   },
824   {
825     EL_EMC_MAGNIFIER,                   -1,
826     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
827     &li.magnify_time,                   10
828   },
829
830   {
831     EL_EMC_MAGIC_BALL,                  -1,
832     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
833     &li.ball_time,                      10
834   },
835   {
836     EL_EMC_MAGIC_BALL,                  -1,
837     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
838     &li.ball_random,                    FALSE
839   },
840   {
841     EL_EMC_MAGIC_BALL,                  -1,
842     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(2),
843     &li.ball_active_initial,            FALSE
844   },
845   {
846     EL_EMC_MAGIC_BALL,                  -1,
847     TYPE_CONTENT_LIST,                  CONF_VALUE_BYTES(1),
848     &li.ball_content,                   EL_EMPTY, NULL,
849     &li.num_ball_contents,              4, MAX_ELEMENT_CONTENTS
850   },
851
852   {
853     EL_SOKOBAN_FIELD_EMPTY,             -1,
854     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
855     &li.sb_fields_needed,               TRUE
856   },
857
858   {
859     EL_SOKOBAN_OBJECT,                  -1,
860     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
861     &li.sb_objects_needed,              TRUE
862   },
863
864   {
865     EL_MM_MCDUFFIN,                     -1,
866     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
867     &li.mm_laser_red,                   FALSE
868   },
869   {
870     EL_MM_MCDUFFIN,                     -1,
871     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(2),
872     &li.mm_laser_green,                 FALSE
873   },
874   {
875     EL_MM_MCDUFFIN,                     -1,
876     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(3),
877     &li.mm_laser_blue,                  TRUE
878   },
879
880   {
881     EL_DF_LASER,                        -1,
882     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
883     &li.df_laser_red,                   TRUE
884   },
885   {
886     EL_DF_LASER,                        -1,
887     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(2),
888     &li.df_laser_green,                 TRUE
889   },
890   {
891     EL_DF_LASER,                        -1,
892     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(3),
893     &li.df_laser_blue,                  FALSE
894   },
895
896   {
897     EL_MM_FUSE_ACTIVE,                  -1,
898     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
899     &li.mm_time_fuse,                   25
900   },
901   {
902     EL_MM_BOMB,                         -1,
903     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
904     &li.mm_time_bomb,                   75
905   },
906   {
907     EL_MM_GRAY_BALL,                    -1,
908     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
909     &li.mm_time_ball,                   75
910   },
911   {
912     EL_MM_STEEL_BLOCK,                  -1,
913     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
914     &li.mm_time_block,                  75
915   },
916   {
917     EL_MM_LIGHTBALL,                    -1,
918     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
919     &li.score[SC_ELEM_BONUS],           10
920   },
921
922   // ---------- unused values -------------------------------------------------
923
924   {
925     EL_UNKNOWN,                         SAVE_CONF_NEVER,
926     TYPE_INTEGER,                       CONF_VALUE_16_BIT(1),
927     &li.score[SC_UNKNOWN_15],           10
928   },
929
930   {
931     -1,                                 -1,
932     -1,                                 -1,
933     NULL,                               -1
934   }
935 };
936
937 static struct LevelFileConfigInfo chunk_config_NOTE[] =
938 {
939   {
940     -1,                                 -1,
941     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
942     &xx_envelope.xsize,                 MAX_ENVELOPE_XSIZE,
943   },
944   {
945     -1,                                 -1,
946     TYPE_INTEGER,                       CONF_VALUE_8_BIT(2),
947     &xx_envelope.ysize,                 MAX_ENVELOPE_YSIZE,
948   },
949
950   {
951     -1,                                 -1,
952     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(3),
953     &xx_envelope.autowrap,              FALSE
954   },
955   {
956     -1,                                 -1,
957     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(4),
958     &xx_envelope.centered,              FALSE
959   },
960
961   {
962     -1,                                 -1,
963     TYPE_STRING,                        CONF_VALUE_BYTES(1),
964     &xx_envelope.text,                  -1, NULL,
965     &xx_string_length_unused,           -1, MAX_ENVELOPE_TEXT_LEN,
966     &xx_default_string_empty[0]
967   },
968
969   {
970     -1,                                 -1,
971     -1,                                 -1,
972     NULL,                               -1
973   }
974 };
975
976 static struct LevelFileConfigInfo chunk_config_CUSX_base[] =
977 {
978   {
979     -1,                                 -1,
980     TYPE_STRING,                        CONF_VALUE_BYTES(1),
981     &xx_ei.description[0],              -1,
982     &yy_ei.description[0],
983     &xx_string_length_unused,           -1, MAX_ELEMENT_NAME_LEN,
984     &xx_default_description[0]
985   },
986
987   {
988     -1,                                 -1,
989     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(1),
990     &xx_ei.properties[EP_BITFIELD_BASE_NR], EP_BITMASK_BASE_DEFAULT,
991     &yy_ei.properties[EP_BITFIELD_BASE_NR]
992   },
993 #if ENABLE_RESERVED_CODE
994   // (reserved for later use)
995   {
996     -1,                                 -1,
997     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(2),
998     &xx_ei.properties[EP_BITFIELD_BASE_NR + 1], EP_BITMASK_DEFAULT,
999     &yy_ei.properties[EP_BITFIELD_BASE_NR + 1]
1000   },
1001 #endif
1002
1003   {
1004     -1,                                 -1,
1005     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
1006     &xx_ei.use_gfx_element,             FALSE,
1007     &yy_ei.use_gfx_element
1008   },
1009   {
1010     -1,                                 -1,
1011     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
1012     &xx_ei.gfx_element_initial,         EL_EMPTY_SPACE,
1013     &yy_ei.gfx_element_initial
1014   },
1015
1016   {
1017     -1,                                 -1,
1018     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(2),
1019     &xx_ei.access_direction,            MV_ALL_DIRECTIONS,
1020     &yy_ei.access_direction
1021   },
1022
1023   {
1024     -1,                                 -1,
1025     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
1026     &xx_ei.collect_score_initial,       10,
1027     &yy_ei.collect_score_initial
1028   },
1029   {
1030     -1,                                 -1,
1031     TYPE_INTEGER,                       CONF_VALUE_16_BIT(3),
1032     &xx_ei.collect_count_initial,       1,
1033     &yy_ei.collect_count_initial
1034   },
1035
1036   {
1037     -1,                                 -1,
1038     TYPE_INTEGER,                       CONF_VALUE_16_BIT(4),
1039     &xx_ei.ce_value_fixed_initial,      0,
1040     &yy_ei.ce_value_fixed_initial
1041   },
1042   {
1043     -1,                                 -1,
1044     TYPE_INTEGER,                       CONF_VALUE_16_BIT(5),
1045     &xx_ei.ce_value_random_initial,     0,
1046     &yy_ei.ce_value_random_initial
1047   },
1048   {
1049     -1,                                 -1,
1050     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(3),
1051     &xx_ei.use_last_ce_value,           FALSE,
1052     &yy_ei.use_last_ce_value
1053   },
1054
1055   {
1056     -1,                                 -1,
1057     TYPE_INTEGER,                       CONF_VALUE_16_BIT(6),
1058     &xx_ei.push_delay_fixed,            8,
1059     &yy_ei.push_delay_fixed
1060   },
1061   {
1062     -1,                                 -1,
1063     TYPE_INTEGER,                       CONF_VALUE_16_BIT(7),
1064     &xx_ei.push_delay_random,           8,
1065     &yy_ei.push_delay_random
1066   },
1067   {
1068     -1,                                 -1,
1069     TYPE_INTEGER,                       CONF_VALUE_16_BIT(8),
1070     &xx_ei.drop_delay_fixed,            0,
1071     &yy_ei.drop_delay_fixed
1072   },
1073   {
1074     -1,                                 -1,
1075     TYPE_INTEGER,                       CONF_VALUE_16_BIT(9),
1076     &xx_ei.drop_delay_random,           0,
1077     &yy_ei.drop_delay_random
1078   },
1079   {
1080     -1,                                 -1,
1081     TYPE_INTEGER,                       CONF_VALUE_16_BIT(10),
1082     &xx_ei.move_delay_fixed,            0,
1083     &yy_ei.move_delay_fixed
1084   },
1085   {
1086     -1,                                 -1,
1087     TYPE_INTEGER,                       CONF_VALUE_16_BIT(11),
1088     &xx_ei.move_delay_random,           0,
1089     &yy_ei.move_delay_random
1090   },
1091   {
1092     -1,                                 -1,
1093     TYPE_INTEGER,                       CONF_VALUE_16_BIT(16),
1094     &xx_ei.step_delay_fixed,            0,
1095     &yy_ei.step_delay_fixed
1096   },
1097   {
1098     -1,                                 -1,
1099     TYPE_INTEGER,                       CONF_VALUE_16_BIT(17),
1100     &xx_ei.step_delay_random,           0,
1101     &yy_ei.step_delay_random
1102   },
1103
1104   {
1105     -1,                                 -1,
1106     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(3),
1107     &xx_ei.move_pattern,                MV_ALL_DIRECTIONS,
1108     &yy_ei.move_pattern
1109   },
1110   {
1111     -1,                                 -1,
1112     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(4),
1113     &xx_ei.move_direction_initial,      MV_START_AUTOMATIC,
1114     &yy_ei.move_direction_initial
1115   },
1116   {
1117     -1,                                 -1,
1118     TYPE_INTEGER,                       CONF_VALUE_8_BIT(5),
1119     &xx_ei.move_stepsize,               TILEX / 8,
1120     &yy_ei.move_stepsize
1121   },
1122
1123   {
1124     -1,                                 -1,
1125     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(12),
1126     &xx_ei.move_enter_element,          EL_EMPTY_SPACE,
1127     &yy_ei.move_enter_element
1128   },
1129   {
1130     -1,                                 -1,
1131     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(13),
1132     &xx_ei.move_leave_element,          EL_EMPTY_SPACE,
1133     &yy_ei.move_leave_element
1134   },
1135   {
1136     -1,                                 -1,
1137     TYPE_INTEGER,                       CONF_VALUE_8_BIT(6),
1138     &xx_ei.move_leave_type,             LEAVE_TYPE_UNLIMITED,
1139     &yy_ei.move_leave_type
1140   },
1141
1142   {
1143     -1,                                 -1,
1144     TYPE_INTEGER,                       CONF_VALUE_8_BIT(7),
1145     &xx_ei.slippery_type,               SLIPPERY_ANY_RANDOM,
1146     &yy_ei.slippery_type
1147   },
1148
1149   {
1150     -1,                                 -1,
1151     TYPE_INTEGER,                       CONF_VALUE_8_BIT(8),
1152     &xx_ei.explosion_type,              EXPLODES_3X3,
1153     &yy_ei.explosion_type
1154   },
1155   {
1156     -1,                                 -1,
1157     TYPE_INTEGER,                       CONF_VALUE_16_BIT(14),
1158     &xx_ei.explosion_delay,             16,
1159     &yy_ei.explosion_delay
1160   },
1161   {
1162     -1,                                 -1,
1163     TYPE_INTEGER,                       CONF_VALUE_16_BIT(15),
1164     &xx_ei.ignition_delay,              8,
1165     &yy_ei.ignition_delay
1166   },
1167
1168   {
1169     -1,                                 -1,
1170     TYPE_CONTENT_LIST,                  CONF_VALUE_BYTES(2),
1171     &xx_ei.content,                     EL_EMPTY_SPACE,
1172     &yy_ei.content,
1173     &xx_num_contents,                   1, 1
1174   },
1175
1176   // ---------- "num_change_pages" must be the last entry ---------------------
1177
1178   {
1179     -1,                                 SAVE_CONF_ALWAYS,
1180     TYPE_INTEGER,                       CONF_VALUE_8_BIT(9),
1181     &xx_ei.num_change_pages,            1,
1182     &yy_ei.num_change_pages
1183   },
1184
1185   {
1186     -1,                                 -1,
1187     -1,                                 -1,
1188     NULL,                               -1,
1189     NULL
1190   }
1191 };
1192
1193 static struct LevelFileConfigInfo chunk_config_CUSX_change[] =
1194 {
1195   // ---------- "current_change_page" must be the first entry -----------------
1196
1197   {
1198     -1,                                 SAVE_CONF_ALWAYS,
1199     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
1200     &xx_current_change_page,            -1
1201   },
1202
1203   // ---------- (the remaining entries can be in any order) -------------------
1204
1205   {
1206     -1,                                 -1,
1207     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(2),
1208     &xx_change.can_change,              FALSE
1209   },
1210
1211   {
1212     -1,                                 -1,
1213     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(1),
1214     &xx_event_bits[0],                  0
1215   },
1216   {
1217     -1,                                 -1,
1218     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(2),
1219     &xx_event_bits[1],                  0
1220   },
1221
1222   {
1223     -1,                                 -1,
1224     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(3),
1225     &xx_change.trigger_player,          CH_PLAYER_ANY
1226   },
1227   {
1228     -1,                                 -1,
1229     TYPE_BITFIELD,                      CONF_VALUE_8_BIT(4),
1230     &xx_change.trigger_side,            CH_SIDE_ANY
1231   },
1232   {
1233     -1,                                 -1,
1234     TYPE_BITFIELD,                      CONF_VALUE_32_BIT(3),
1235     &xx_change.trigger_page,            CH_PAGE_ANY
1236   },
1237
1238   {
1239     -1,                                 -1,
1240     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
1241     &xx_change.target_element,          EL_EMPTY_SPACE
1242   },
1243
1244   {
1245     -1,                                 -1,
1246     TYPE_INTEGER,                       CONF_VALUE_16_BIT(2),
1247     &xx_change.delay_fixed,             0
1248   },
1249   {
1250     -1,                                 -1,
1251     TYPE_INTEGER,                       CONF_VALUE_16_BIT(3),
1252     &xx_change.delay_random,            0
1253   },
1254   {
1255     -1,                                 -1,
1256     TYPE_INTEGER,                       CONF_VALUE_16_BIT(4),
1257     &xx_change.delay_frames,            FRAMES_PER_SECOND
1258   },
1259
1260   {
1261     -1,                                 -1,
1262     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(5),
1263     &xx_change.initial_trigger_element, EL_EMPTY_SPACE
1264   },
1265
1266   {
1267     -1,                                 -1,
1268     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(6),
1269     &xx_change.explode,                 FALSE
1270   },
1271   {
1272     -1,                                 -1,
1273     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(7),
1274     &xx_change.use_target_content,      FALSE
1275   },
1276   {
1277     -1,                                 -1,
1278     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(8),
1279     &xx_change.only_if_complete,        FALSE
1280   },
1281   {
1282     -1,                                 -1,
1283     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
1284     &xx_change.use_random_replace,      FALSE
1285   },
1286   {
1287     -1,                                 -1,
1288     TYPE_INTEGER,                       CONF_VALUE_8_BIT(10),
1289     &xx_change.random_percentage,       100
1290   },
1291   {
1292     -1,                                 -1,
1293     TYPE_INTEGER,                       CONF_VALUE_8_BIT(11),
1294     &xx_change.replace_when,            CP_WHEN_EMPTY
1295   },
1296
1297   {
1298     -1,                                 -1,
1299     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(12),
1300     &xx_change.has_action,              FALSE
1301   },
1302   {
1303     -1,                                 -1,
1304     TYPE_INTEGER,                       CONF_VALUE_8_BIT(13),
1305     &xx_change.action_type,             CA_NO_ACTION
1306   },
1307   {
1308     -1,                                 -1,
1309     TYPE_INTEGER,                       CONF_VALUE_8_BIT(14),
1310     &xx_change.action_mode,             CA_MODE_UNDEFINED
1311   },
1312   {
1313     -1,                                 -1,
1314     TYPE_INTEGER,                       CONF_VALUE_16_BIT(6),
1315     &xx_change.action_arg,              CA_ARG_UNDEFINED
1316   },
1317
1318   {
1319     -1,                                 -1,
1320     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(7),
1321     &xx_change.action_element,          EL_EMPTY_SPACE
1322   },
1323
1324   {
1325     -1,                                 -1,
1326     TYPE_CONTENT_LIST,                  CONF_VALUE_BYTES(1),
1327     &xx_change.target_content,          EL_EMPTY_SPACE, NULL,
1328     &xx_num_contents,                   1, 1
1329   },
1330
1331   {
1332     -1,                                 -1,
1333     -1,                                 -1,
1334     NULL,                               -1
1335   }
1336 };
1337
1338 static struct LevelFileConfigInfo chunk_config_GRPX[] =
1339 {
1340   {
1341     -1,                                 -1,
1342     TYPE_STRING,                        CONF_VALUE_BYTES(1),
1343     &xx_ei.description[0],              -1, NULL,
1344     &xx_string_length_unused,           -1, MAX_ELEMENT_NAME_LEN,
1345     &xx_default_description[0]
1346   },
1347
1348   {
1349     -1,                                 -1,
1350     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(1),
1351     &xx_ei.use_gfx_element,             FALSE
1352   },
1353   {
1354     -1,                                 -1,
1355     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
1356     &xx_ei.gfx_element_initial,         EL_EMPTY_SPACE
1357   },
1358
1359   {
1360     -1,                                 -1,
1361     TYPE_INTEGER,                       CONF_VALUE_8_BIT(2),
1362     &xx_group.choice_mode,              ANIM_RANDOM
1363   },
1364
1365   {
1366     -1,                                 -1,
1367     TYPE_ELEMENT_LIST,                  CONF_VALUE_BYTES(2),
1368     &xx_group.element[0],               EL_EMPTY_SPACE, NULL,
1369     &xx_group.num_elements,             1, MAX_ELEMENTS_IN_GROUP
1370   },
1371
1372   {
1373     -1,                                 -1,
1374     -1,                                 -1,
1375     NULL,                               -1
1376   }
1377 };
1378
1379 static struct LevelFileConfigInfo chunk_config_CONF[] =         // (OBSOLETE)
1380 {
1381   {
1382     EL_PLAYER_1,                        -1,
1383     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(9),
1384     &li.block_snap_field,               TRUE
1385   },
1386   {
1387     EL_PLAYER_1,                        -1,
1388     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(13),
1389     &li.continuous_snapping,            TRUE
1390   },
1391   {
1392     EL_PLAYER_1,                        -1,
1393     TYPE_INTEGER,                       CONF_VALUE_8_BIT(1),
1394     &li.initial_player_stepsize[0],     STEPSIZE_NORMAL
1395   },
1396   {
1397     EL_PLAYER_1,                        -1,
1398     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(10),
1399     &li.use_start_element[0],           FALSE
1400   },
1401   {
1402     EL_PLAYER_1,                        -1,
1403     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(1),
1404     &li.start_element[0],               EL_PLAYER_1
1405   },
1406   {
1407     EL_PLAYER_1,                        -1,
1408     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(11),
1409     &li.use_artwork_element[0],         FALSE
1410   },
1411   {
1412     EL_PLAYER_1,                        -1,
1413     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(2),
1414     &li.artwork_element[0],             EL_PLAYER_1
1415   },
1416   {
1417     EL_PLAYER_1,                        -1,
1418     TYPE_BOOLEAN,                       CONF_VALUE_8_BIT(12),
1419     &li.use_explosion_element[0],       FALSE
1420   },
1421   {
1422     EL_PLAYER_1,                        -1,
1423     TYPE_ELEMENT,                       CONF_VALUE_16_BIT(3),
1424     &li.explosion_element[0],           EL_PLAYER_1
1425   },
1426
1427   {
1428     -1,                                 -1,
1429     -1,                                 -1,
1430     NULL,                               -1
1431   }
1432 };
1433
1434 static struct
1435 {
1436   int filetype;
1437   char *id;
1438 }
1439 filetype_id_list[] =
1440 {
1441   { LEVEL_FILE_TYPE_RND,        "RND"   },
1442   { LEVEL_FILE_TYPE_BD,         "BD"    },
1443   { LEVEL_FILE_TYPE_EM,         "EM"    },
1444   { LEVEL_FILE_TYPE_SP,         "SP"    },
1445   { LEVEL_FILE_TYPE_DX,         "DX"    },
1446   { LEVEL_FILE_TYPE_SB,         "SB"    },
1447   { LEVEL_FILE_TYPE_DC,         "DC"    },
1448   { LEVEL_FILE_TYPE_MM,         "MM"    },
1449   { LEVEL_FILE_TYPE_MM,         "DF"    },
1450   { -1,                         NULL    },
1451 };
1452
1453
1454 // ============================================================================
1455 // level file functions
1456 // ============================================================================
1457
1458 static boolean check_special_flags(char *flag)
1459 {
1460   if (strEqual(options.special_flags, flag) ||
1461       strEqual(leveldir_current->special_flags, flag))
1462     return TRUE;
1463
1464   return FALSE;
1465 }
1466
1467 static struct DateInfo getCurrentDate(void)
1468 {
1469   time_t epoch_seconds = time(NULL);
1470   struct tm *now = localtime(&epoch_seconds);
1471   struct DateInfo date;
1472
1473   date.year  = now->tm_year + 1900;
1474   date.month = now->tm_mon  + 1;
1475   date.day   = now->tm_mday;
1476
1477   date.src   = DATE_SRC_CLOCK;
1478
1479   return date;
1480 }
1481
1482 static void resetEventFlags(struct ElementChangeInfo *change)
1483 {
1484   int i;
1485
1486   for (i = 0; i < NUM_CHANGE_EVENTS; i++)
1487     change->has_event[i] = FALSE;
1488 }
1489
1490 static void resetEventBits(void)
1491 {
1492   int i;
1493
1494   for (i = 0; i < NUM_CE_BITFIELDS; i++)
1495     xx_event_bits[i] = 0;
1496 }
1497
1498 static void setEventFlagsFromEventBits(struct ElementChangeInfo *change)
1499 {
1500   int i;
1501
1502   /* important: only change event flag if corresponding event bit is set
1503      (this is because all xx_event_bits[] values are loaded separately,
1504      and all xx_event_bits[] values are set back to zero before loading
1505      another value xx_event_bits[x] (each value representing 32 flags)) */
1506
1507   for (i = 0; i < NUM_CHANGE_EVENTS; i++)
1508     if (xx_event_bits[CH_EVENT_BITFIELD_NR(i)] & CH_EVENT_BIT(i))
1509       change->has_event[i] = TRUE;
1510 }
1511
1512 static void setEventBitsFromEventFlags(struct ElementChangeInfo *change)
1513 {
1514   int i;
1515
1516   /* in contrast to the above function setEventFlagsFromEventBits(), it
1517      would also be possible to set all bits in xx_event_bits[] to 0 or 1
1518      depending on the corresponding change->has_event[i] values here, as
1519      all xx_event_bits[] values are reset in resetEventBits() before */
1520
1521   for (i = 0; i < NUM_CHANGE_EVENTS; i++)
1522     if (change->has_event[i])
1523       xx_event_bits[CH_EVENT_BITFIELD_NR(i)] |= CH_EVENT_BIT(i);
1524 }
1525
1526 static char *getDefaultElementDescription(struct ElementInfo *ei)
1527 {
1528   static char description[MAX_ELEMENT_NAME_LEN + 1];
1529   char *default_description = (ei->custom_description != NULL ?
1530                                ei->custom_description :
1531                                ei->editor_description);
1532   int i;
1533
1534   // always start with reliable default values
1535   for (i = 0; i < MAX_ELEMENT_NAME_LEN + 1; i++)
1536     description[i] = '\0';
1537
1538   // truncate element description to MAX_ELEMENT_NAME_LEN bytes
1539   strncpy(description, default_description, MAX_ELEMENT_NAME_LEN);
1540
1541   return &description[0];
1542 }
1543
1544 static void setElementDescriptionToDefault(struct ElementInfo *ei)
1545 {
1546   char *default_description = getDefaultElementDescription(ei);
1547   int i;
1548
1549   for (i = 0; i < MAX_ELEMENT_NAME_LEN + 1; i++)
1550     ei->description[i] = default_description[i];
1551 }
1552
1553 static void setConfigToDefaultsFromConfigList(struct LevelFileConfigInfo *conf)
1554 {
1555   int i;
1556
1557   for (i = 0; conf[i].data_type != -1; i++)
1558   {
1559     int default_value = conf[i].default_value;
1560     int data_type = conf[i].data_type;
1561     int conf_type = conf[i].conf_type;
1562     int byte_mask = conf_type & CONF_MASK_BYTES;
1563
1564     if (byte_mask == CONF_MASK_MULTI_BYTES)
1565     {
1566       int default_num_entities = conf[i].default_num_entities;
1567       int max_num_entities = conf[i].max_num_entities;
1568
1569       *(int *)(conf[i].num_entities) = default_num_entities;
1570
1571       if (data_type == TYPE_STRING)
1572       {
1573         char *default_string = conf[i].default_string;
1574         char *string = (char *)(conf[i].value);
1575
1576         strncpy(string, default_string, max_num_entities);
1577       }
1578       else if (data_type == TYPE_ELEMENT_LIST)
1579       {
1580         int *element_array = (int *)(conf[i].value);
1581         int j;
1582
1583         for (j = 0; j < max_num_entities; j++)
1584           element_array[j] = default_value;
1585       }
1586       else if (data_type == TYPE_CONTENT_LIST)
1587       {
1588         struct Content *content = (struct Content *)(conf[i].value);
1589         int c, x, y;
1590
1591         for (c = 0; c < max_num_entities; c++)
1592           for (y = 0; y < 3; y++)
1593             for (x = 0; x < 3; x++)
1594               content[c].e[x][y] = default_value;
1595       }
1596     }
1597     else        // constant size configuration data (1, 2 or 4 bytes)
1598     {
1599       if (data_type == TYPE_BOOLEAN)
1600         *(boolean *)(conf[i].value) = default_value;
1601       else
1602         *(int *)    (conf[i].value) = default_value;
1603     }
1604   }
1605 }
1606
1607 static void copyConfigFromConfigList(struct LevelFileConfigInfo *conf)
1608 {
1609   int i;
1610
1611   for (i = 0; conf[i].data_type != -1; i++)
1612   {
1613     int data_type = conf[i].data_type;
1614     int conf_type = conf[i].conf_type;
1615     int byte_mask = conf_type & CONF_MASK_BYTES;
1616
1617     if (byte_mask == CONF_MASK_MULTI_BYTES)
1618     {
1619       int max_num_entities = conf[i].max_num_entities;
1620
1621       if (data_type == TYPE_STRING)
1622       {
1623         char *string      = (char *)(conf[i].value);
1624         char *string_copy = (char *)(conf[i].value_copy);
1625
1626         strncpy(string_copy, string, max_num_entities);
1627       }
1628       else if (data_type == TYPE_ELEMENT_LIST)
1629       {
1630         int *element_array      = (int *)(conf[i].value);
1631         int *element_array_copy = (int *)(conf[i].value_copy);
1632         int j;
1633
1634         for (j = 0; j < max_num_entities; j++)
1635           element_array_copy[j] = element_array[j];
1636       }
1637       else if (data_type == TYPE_CONTENT_LIST)
1638       {
1639         struct Content *content      = (struct Content *)(conf[i].value);
1640         struct Content *content_copy = (struct Content *)(conf[i].value_copy);
1641         int c, x, y;
1642
1643         for (c = 0; c < max_num_entities; c++)
1644           for (y = 0; y < 3; y++)
1645             for (x = 0; x < 3; x++)
1646               content_copy[c].e[x][y] = content[c].e[x][y];
1647       }
1648     }
1649     else        // constant size configuration data (1, 2 or 4 bytes)
1650     {
1651       if (data_type == TYPE_BOOLEAN)
1652         *(boolean *)(conf[i].value_copy) = *(boolean *)(conf[i].value);
1653       else
1654         *(int *)    (conf[i].value_copy) = *(int *)    (conf[i].value);
1655     }
1656   }
1657 }
1658
1659 void copyElementInfo(struct ElementInfo *ei_from, struct ElementInfo *ei_to)
1660 {
1661   int i;
1662
1663   xx_ei = *ei_from;     // copy element data into temporary buffer
1664   yy_ei = *ei_to;       // copy element data into temporary buffer
1665
1666   copyConfigFromConfigList(chunk_config_CUSX_base);
1667
1668   *ei_from = xx_ei;
1669   *ei_to   = yy_ei;
1670
1671   // ---------- reinitialize and copy change pages ----------
1672
1673   ei_to->num_change_pages = ei_from->num_change_pages;
1674   ei_to->current_change_page = ei_from->current_change_page;
1675
1676   setElementChangePages(ei_to, ei_to->num_change_pages);
1677
1678   for (i = 0; i < ei_to->num_change_pages; i++)
1679     ei_to->change_page[i] = ei_from->change_page[i];
1680
1681   // ---------- copy group element info ----------
1682   if (ei_from->group != NULL && ei_to->group != NULL)   // group or internal
1683     *ei_to->group = *ei_from->group;
1684
1685   // mark this custom element as modified
1686   ei_to->modified_settings = TRUE;
1687 }
1688
1689 void setElementChangePages(struct ElementInfo *ei, int change_pages)
1690 {
1691   int change_page_size = sizeof(struct ElementChangeInfo);
1692
1693   ei->num_change_pages = MAX(1, change_pages);
1694
1695   ei->change_page =
1696     checked_realloc(ei->change_page, ei->num_change_pages * change_page_size);
1697
1698   if (ei->current_change_page >= ei->num_change_pages)
1699     ei->current_change_page = ei->num_change_pages - 1;
1700
1701   ei->change = &ei->change_page[ei->current_change_page];
1702 }
1703
1704 void setElementChangeInfoToDefaults(struct ElementChangeInfo *change)
1705 {
1706   xx_change = *change;          // copy change data into temporary buffer
1707
1708   setConfigToDefaultsFromConfigList(chunk_config_CUSX_change);
1709
1710   *change = xx_change;
1711
1712   resetEventFlags(change);
1713
1714   change->direct_action = 0;
1715   change->other_action = 0;
1716
1717   change->pre_change_function = NULL;
1718   change->change_function = NULL;
1719   change->post_change_function = NULL;
1720 }
1721
1722 static void setLevelInfoToDefaults_Level(struct LevelInfo *level)
1723 {
1724   int i, x, y;
1725
1726   li = *level;          // copy level data into temporary buffer
1727   setConfigToDefaultsFromConfigList(chunk_config_INFO);
1728   *level = li;          // copy temporary buffer back to level data
1729
1730   setLevelInfoToDefaults_EM();
1731   setLevelInfoToDefaults_SP();
1732   setLevelInfoToDefaults_MM();
1733
1734   level->native_em_level = &native_em_level;
1735   level->native_sp_level = &native_sp_level;
1736   level->native_mm_level = &native_mm_level;
1737
1738   level->file_version = FILE_VERSION_ACTUAL;
1739   level->game_version = GAME_VERSION_ACTUAL;
1740
1741   level->creation_date = getCurrentDate();
1742
1743   level->encoding_16bit_field  = TRUE;
1744   level->encoding_16bit_yamyam = TRUE;
1745   level->encoding_16bit_amoeba = TRUE;
1746
1747   // clear level name and level author string buffers
1748   for (i = 0; i < MAX_LEVEL_NAME_LEN; i++)
1749     level->name[i] = '\0';
1750   for (i = 0; i < MAX_LEVEL_AUTHOR_LEN; i++)
1751     level->author[i] = '\0';
1752
1753   // set level name and level author to default values
1754   strcpy(level->name, NAMELESS_LEVEL_NAME);
1755   strcpy(level->author, ANONYMOUS_NAME);
1756
1757   // set level playfield to playable default level with player and exit
1758   for (x = 0; x < MAX_LEV_FIELDX; x++)
1759     for (y = 0; y < MAX_LEV_FIELDY; y++)
1760       level->field[x][y] = EL_SAND;
1761
1762   level->field[0][0] = EL_PLAYER_1;
1763   level->field[STD_LEV_FIELDX - 1][STD_LEV_FIELDY - 1] = EL_EXIT_CLOSED;
1764
1765   BorderElement = EL_STEELWALL;
1766
1767   // detect custom elements when loading them
1768   level->file_has_custom_elements = FALSE;
1769
1770   // set all bug compatibility flags to "false" => do not emulate this bug
1771   level->use_action_after_change_bug = FALSE;
1772
1773   if (leveldir_current)
1774   {
1775     // try to determine better author name than 'anonymous'
1776     if (!strEqual(leveldir_current->author, ANONYMOUS_NAME))
1777     {
1778       strncpy(level->author, leveldir_current->author, MAX_LEVEL_AUTHOR_LEN);
1779       level->author[MAX_LEVEL_AUTHOR_LEN] = '\0';
1780     }
1781     else
1782     {
1783       switch (LEVELCLASS(leveldir_current))
1784       {
1785         case LEVELCLASS_TUTORIAL:
1786           strcpy(level->author, PROGRAM_AUTHOR_STRING);
1787           break;
1788
1789         case LEVELCLASS_CONTRIB:
1790           strncpy(level->author, leveldir_current->name, MAX_LEVEL_AUTHOR_LEN);
1791           level->author[MAX_LEVEL_AUTHOR_LEN] = '\0';
1792           break;
1793
1794         case LEVELCLASS_PRIVATE:
1795           strncpy(level->author, getRealName(), MAX_LEVEL_AUTHOR_LEN);
1796           level->author[MAX_LEVEL_AUTHOR_LEN] = '\0';
1797           break;
1798
1799         default:
1800           // keep default value
1801           break;
1802       }
1803     }
1804   }
1805 }
1806
1807 static void setLevelInfoToDefaults_Elements(struct LevelInfo *level)
1808 {
1809   static boolean clipboard_elements_initialized = FALSE;
1810   int i;
1811
1812   InitElementPropertiesStatic();
1813
1814   li = *level;          // copy level data into temporary buffer
1815   setConfigToDefaultsFromConfigList(chunk_config_ELEM);
1816   *level = li;          // copy temporary buffer back to level data
1817
1818   for (i = 0; i < MAX_NUM_ELEMENTS; i++)
1819   {
1820     int element = i;
1821     struct ElementInfo *ei = &element_info[element];
1822
1823     // never initialize clipboard elements after the very first time
1824     // (to be able to use clipboard elements between several levels)
1825     if (IS_CLIPBOARD_ELEMENT(element) && clipboard_elements_initialized)
1826       continue;
1827
1828     if (IS_ENVELOPE(element))
1829     {
1830       int envelope_nr = element - EL_ENVELOPE_1;
1831
1832       setConfigToDefaultsFromConfigList(chunk_config_NOTE);
1833
1834       level->envelope[envelope_nr] = xx_envelope;
1835     }
1836
1837     if (IS_CUSTOM_ELEMENT(element) ||
1838         IS_GROUP_ELEMENT(element) ||
1839         IS_INTERNAL_ELEMENT(element))
1840     {
1841       xx_ei = *ei;      // copy element data into temporary buffer
1842
1843       setConfigToDefaultsFromConfigList(chunk_config_CUSX_base);
1844
1845       *ei = xx_ei;
1846     }
1847
1848     setElementChangePages(ei, 1);
1849     setElementChangeInfoToDefaults(ei->change);
1850
1851     if (IS_CUSTOM_ELEMENT(element) ||
1852         IS_GROUP_ELEMENT(element) ||
1853         IS_INTERNAL_ELEMENT(element))
1854     {
1855       setElementDescriptionToDefault(ei);
1856
1857       ei->modified_settings = FALSE;
1858     }
1859
1860     if (IS_CUSTOM_ELEMENT(element) ||
1861         IS_INTERNAL_ELEMENT(element))
1862     {
1863       // internal values used in level editor
1864
1865       ei->access_type = 0;
1866       ei->access_layer = 0;
1867       ei->access_protected = 0;
1868       ei->walk_to_action = 0;
1869       ei->smash_targets = 0;
1870       ei->deadliness = 0;
1871
1872       ei->can_explode_by_fire = FALSE;
1873       ei->can_explode_smashed = FALSE;
1874       ei->can_explode_impact = FALSE;
1875
1876       ei->current_change_page = 0;
1877     }
1878
1879     if (IS_GROUP_ELEMENT(element) ||
1880         IS_INTERNAL_ELEMENT(element))
1881     {
1882       struct ElementGroupInfo *group;
1883
1884       // initialize memory for list of elements in group
1885       if (ei->group == NULL)
1886         ei->group = checked_malloc(sizeof(struct ElementGroupInfo));
1887
1888       group = ei->group;
1889
1890       xx_group = *group;        // copy group data into temporary buffer
1891
1892       setConfigToDefaultsFromConfigList(chunk_config_GRPX);
1893
1894       *group = xx_group;
1895     }
1896   }
1897
1898   clipboard_elements_initialized = TRUE;
1899 }
1900
1901 static void setLevelInfoToDefaults(struct LevelInfo *level,
1902                                    boolean level_info_only,
1903                                    boolean reset_file_status)
1904 {
1905   setLevelInfoToDefaults_Level(level);
1906
1907   if (!level_info_only)
1908     setLevelInfoToDefaults_Elements(level);
1909
1910   if (reset_file_status)
1911   {
1912     level->no_valid_file = FALSE;
1913     level->no_level_file = FALSE;
1914   }
1915
1916   level->changed = FALSE;
1917 }
1918
1919 static void setFileInfoToDefaults(struct LevelFileInfo *level_file_info)
1920 {
1921   level_file_info->nr = 0;
1922   level_file_info->type = LEVEL_FILE_TYPE_UNKNOWN;
1923   level_file_info->packed = FALSE;
1924
1925   setString(&level_file_info->basename, NULL);
1926   setString(&level_file_info->filename, NULL);
1927 }
1928
1929 int getMappedElement_SB(int, boolean);
1930
1931 static void ActivateLevelTemplate(void)
1932 {
1933   int x, y;
1934
1935   if (check_special_flags("load_xsb_to_ces"))
1936   {
1937     // fill smaller playfields with padding "beyond border wall" elements
1938     if (level.fieldx < level_template.fieldx ||
1939         level.fieldy < level_template.fieldy)
1940     {
1941       short field[level.fieldx][level.fieldy];
1942       int new_fieldx = MAX(level.fieldx, level_template.fieldx);
1943       int new_fieldy = MAX(level.fieldy, level_template.fieldy);
1944       int pos_fieldx = (new_fieldx - level.fieldx) / 2;
1945       int pos_fieldy = (new_fieldy - level.fieldy) / 2;
1946
1947       // copy old playfield (which is smaller than the visible area)
1948       for (y = 0; y < level.fieldy; y++) for (x = 0; x < level.fieldx; x++)
1949         field[x][y] = level.field[x][y];
1950
1951       // fill new, larger playfield with "beyond border wall" elements
1952       for (y = 0; y < new_fieldy; y++) for (x = 0; x < new_fieldx; x++)
1953         level.field[x][y] = getMappedElement_SB('_', TRUE);
1954
1955       // copy the old playfield to the middle of the new playfield
1956       for (y = 0; y < level.fieldy; y++) for (x = 0; x < level.fieldx; x++)
1957         level.field[pos_fieldx + x][pos_fieldy + y] = field[x][y];
1958
1959       level.fieldx = new_fieldx;
1960       level.fieldy = new_fieldy;
1961     }
1962   }
1963
1964   // Currently there is no special action needed to activate the template
1965   // data, because 'element_info' property settings overwrite the original
1966   // level data, while all other variables do not change.
1967
1968   // Exception: 'from_level_template' elements in the original level playfield
1969   // are overwritten with the corresponding elements at the same position in
1970   // playfield from the level template.
1971
1972   for (x = 0; x < level.fieldx; x++)
1973     for (y = 0; y < level.fieldy; y++)
1974       if (level.field[x][y] == EL_FROM_LEVEL_TEMPLATE)
1975         level.field[x][y] = level_template.field[x][y];
1976
1977   if (check_special_flags("load_xsb_to_ces"))
1978   {
1979     struct LevelInfo level_backup = level;
1980
1981     // overwrite all individual level settings from template level settings
1982     level = level_template;
1983
1984     // restore level file info
1985     level.file_info = level_backup.file_info;
1986
1987     // restore playfield size
1988     level.fieldx = level_backup.fieldx;
1989     level.fieldy = level_backup.fieldy;
1990
1991     // restore playfield content
1992     for (x = 0; x < level.fieldx; x++)
1993       for (y = 0; y < level.fieldy; y++)
1994         level.field[x][y] = level_backup.field[x][y];
1995
1996     // restore name and author from individual level
1997     strcpy(level.name,   level_backup.name);
1998     strcpy(level.author, level_backup.author);
1999
2000     // restore flag "use_custom_template"
2001     level.use_custom_template = level_backup.use_custom_template;
2002   }
2003 }
2004
2005 static char *getLevelFilenameFromBasename(char *basename)
2006 {
2007   static char *filename = NULL;
2008
2009   checked_free(filename);
2010
2011   filename = getPath2(getCurrentLevelDir(), basename);
2012
2013   return filename;
2014 }
2015
2016 static int getFileTypeFromBasename(char *basename)
2017 {
2018   // !!! ALSO SEE COMMENT IN checkForPackageFromBasename() !!!
2019
2020   static char *filename = NULL;
2021   struct stat file_status;
2022
2023   // ---------- try to determine file type from filename ----------
2024
2025   // check for typical filename of a Supaplex level package file
2026   if (strlen(basename) == 10 && strPrefixLower(basename, "levels.d"))
2027     return LEVEL_FILE_TYPE_SP;
2028
2029   // check for typical filename of a Diamond Caves II level package file
2030   if (strSuffixLower(basename, ".dc") ||
2031       strSuffixLower(basename, ".dc2"))
2032     return LEVEL_FILE_TYPE_DC;
2033
2034   // check for typical filename of a Sokoban level package file
2035   if (strSuffixLower(basename, ".xsb") &&
2036       strchr(basename, '%') == NULL)
2037     return LEVEL_FILE_TYPE_SB;
2038
2039   // ---------- try to determine file type from filesize ----------
2040
2041   checked_free(filename);
2042   filename = getPath2(getCurrentLevelDir(), basename);
2043
2044   if (stat(filename, &file_status) == 0)
2045   {
2046     // check for typical filesize of a Supaplex level package file
2047     if (file_status.st_size == 170496)
2048       return LEVEL_FILE_TYPE_SP;
2049   }
2050
2051   return LEVEL_FILE_TYPE_UNKNOWN;
2052 }
2053
2054 static int getFileTypeFromMagicBytes(char *filename, int type)
2055 {
2056   File *file;
2057
2058   if ((file = openFile(filename, MODE_READ)))
2059   {
2060     char chunk_name[CHUNK_ID_LEN + 1];
2061
2062     getFileChunkBE(file, chunk_name, NULL);
2063
2064     if (strEqual(chunk_name, "MMII") ||
2065         strEqual(chunk_name, "MIRR"))
2066       type = LEVEL_FILE_TYPE_MM;
2067
2068     closeFile(file);
2069   }
2070
2071   return type;
2072 }
2073
2074 static boolean checkForPackageFromBasename(char *basename)
2075 {
2076   // !!! WON'T WORK ANYMORE IF getFileTypeFromBasename() ALSO DETECTS !!!
2077   // !!! SINGLE LEVELS (CURRENTLY ONLY DETECTS LEVEL PACKAGES         !!!
2078
2079   return (getFileTypeFromBasename(basename) != LEVEL_FILE_TYPE_UNKNOWN);
2080 }
2081
2082 static char *getSingleLevelBasenameExt(int nr, char *extension)
2083 {
2084   static char basename[MAX_FILENAME_LEN];
2085
2086   if (nr < 0)
2087     sprintf(basename, "%s", LEVELTEMPLATE_FILENAME);
2088   else
2089     sprintf(basename, "%03d.%s", nr, extension);
2090
2091   return basename;
2092 }
2093
2094 static char *getSingleLevelBasename(int nr)
2095 {
2096   return getSingleLevelBasenameExt(nr, LEVELFILE_EXTENSION);
2097 }
2098
2099 static char *getPackedLevelBasename(int type)
2100 {
2101   static char basename[MAX_FILENAME_LEN];
2102   char *directory = getCurrentLevelDir();
2103   Directory *dir;
2104   DirectoryEntry *dir_entry;
2105
2106   strcpy(basename, UNDEFINED_FILENAME);         // default: undefined file
2107
2108   if ((dir = openDirectory(directory)) == NULL)
2109   {
2110     Warn("cannot read current level directory '%s'", directory);
2111
2112     return basename;
2113   }
2114
2115   while ((dir_entry = readDirectory(dir)) != NULL)      // loop all entries
2116   {
2117     char *entry_basename = dir_entry->basename;
2118     int entry_type = getFileTypeFromBasename(entry_basename);
2119
2120     if (entry_type != LEVEL_FILE_TYPE_UNKNOWN)  // found valid level package
2121     {
2122       if (type == LEVEL_FILE_TYPE_UNKNOWN ||
2123           type == entry_type)
2124       {
2125         strcpy(basename, entry_basename);
2126
2127         break;
2128       }
2129     }
2130   }
2131
2132   closeDirectory(dir);
2133
2134   return basename;
2135 }
2136
2137 static char *getSingleLevelFilename(int nr)
2138 {
2139   return getLevelFilenameFromBasename(getSingleLevelBasename(nr));
2140 }
2141
2142 #if ENABLE_UNUSED_CODE
2143 static char *getPackedLevelFilename(int type)
2144 {
2145   return getLevelFilenameFromBasename(getPackedLevelBasename(type));
2146 }
2147 #endif
2148
2149 char *getDefaultLevelFilename(int nr)
2150 {
2151   return getSingleLevelFilename(nr);
2152 }
2153
2154 #if ENABLE_UNUSED_CODE
2155 static void setLevelFileInfo_SingleLevelFilename(struct LevelFileInfo *lfi,
2156                                                  int type)
2157 {
2158   lfi->type = type;
2159   lfi->packed = FALSE;
2160
2161   setString(&lfi->basename, getSingleLevelBasename(lfi->nr, lfi->type));
2162   setString(&lfi->filename, getLevelFilenameFromBasename(lfi->basename));
2163 }
2164 #endif
2165
2166 static void setLevelFileInfo_FormatLevelFilename(struct LevelFileInfo *lfi,
2167                                                  int type, char *format, ...)
2168 {
2169   static char basename[MAX_FILENAME_LEN];
2170   va_list ap;
2171
2172   va_start(ap, format);
2173   vsprintf(basename, format, ap);
2174   va_end(ap);
2175
2176   lfi->type = type;
2177   lfi->packed = FALSE;
2178
2179   setString(&lfi->basename, basename);
2180   setString(&lfi->filename, getLevelFilenameFromBasename(lfi->basename));
2181 }
2182
2183 static void setLevelFileInfo_PackedLevelFilename(struct LevelFileInfo *lfi,
2184                                                  int type)
2185 {
2186   lfi->type = type;
2187   lfi->packed = TRUE;
2188
2189   setString(&lfi->basename, getPackedLevelBasename(lfi->type));
2190   setString(&lfi->filename, getLevelFilenameFromBasename(lfi->basename));
2191 }
2192
2193 static int getFiletypeFromID(char *filetype_id)
2194 {
2195   char *filetype_id_lower;
2196   int filetype = LEVEL_FILE_TYPE_UNKNOWN;
2197   int i;
2198
2199   if (filetype_id == NULL)
2200     return LEVEL_FILE_TYPE_UNKNOWN;
2201
2202   filetype_id_lower = getStringToLower(filetype_id);
2203
2204   for (i = 0; filetype_id_list[i].id != NULL; i++)
2205   {
2206     char *id_lower = getStringToLower(filetype_id_list[i].id);
2207     
2208     if (strEqual(filetype_id_lower, id_lower))
2209       filetype = filetype_id_list[i].filetype;
2210
2211     free(id_lower);
2212
2213     if (filetype != LEVEL_FILE_TYPE_UNKNOWN)
2214       break;
2215   }
2216
2217   free(filetype_id_lower);
2218
2219   return filetype;
2220 }
2221
2222 char *getLocalLevelTemplateFilename(void)
2223 {
2224   return getDefaultLevelFilename(-1);
2225 }
2226
2227 char *getGlobalLevelTemplateFilename(void)
2228 {
2229   // global variable "leveldir_current" must be modified in the loop below
2230   LevelDirTree *leveldir_current_last = leveldir_current;
2231   char *filename = NULL;
2232
2233   // check for template level in path from current to topmost tree node
2234
2235   while (leveldir_current != NULL)
2236   {
2237     filename = getDefaultLevelFilename(-1);
2238
2239     if (fileExists(filename))
2240       break;
2241
2242     leveldir_current = leveldir_current->node_parent;
2243   }
2244
2245   // restore global variable "leveldir_current" modified in above loop
2246   leveldir_current = leveldir_current_last;
2247
2248   return filename;
2249 }
2250
2251 static void determineLevelFileInfo_Filename(struct LevelFileInfo *lfi)
2252 {
2253   int nr = lfi->nr;
2254
2255   // special case: level number is negative => check for level template file
2256   if (nr < 0)
2257   {
2258     setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_RND,
2259                                          getSingleLevelBasename(-1));
2260
2261     // replace local level template filename with global template filename
2262     setString(&lfi->filename, getGlobalLevelTemplateFilename());
2263
2264     // no fallback if template file not existing
2265     return;
2266   }
2267
2268   // special case: check for file name/pattern specified in "levelinfo.conf"
2269   if (leveldir_current->level_filename != NULL)
2270   {
2271     int filetype = getFiletypeFromID(leveldir_current->level_filetype);
2272
2273     setLevelFileInfo_FormatLevelFilename(lfi, filetype,
2274                                          leveldir_current->level_filename, nr);
2275
2276     lfi->packed = checkForPackageFromBasename(leveldir_current->level_filename);
2277
2278     if (fileExists(lfi->filename))
2279       return;
2280   }
2281   else if (leveldir_current->level_filetype != NULL)
2282   {
2283     int filetype = getFiletypeFromID(leveldir_current->level_filetype);
2284
2285     // check for specified native level file with standard file name
2286     setLevelFileInfo_FormatLevelFilename(lfi, filetype,
2287                                          "%03d.%s", nr, LEVELFILE_EXTENSION);
2288     if (fileExists(lfi->filename))
2289       return;
2290   }
2291
2292   // check for native Rocks'n'Diamonds level file
2293   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_RND,
2294                                        "%03d.%s", nr, LEVELFILE_EXTENSION);
2295   if (fileExists(lfi->filename))
2296     return;
2297
2298   // check for Emerald Mine level file (V1)
2299   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "a%c%c",
2300                                        'a' + (nr / 10) % 26, '0' + nr % 10);
2301   if (fileExists(lfi->filename))
2302     return;
2303   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "A%c%c",
2304                                        'A' + (nr / 10) % 26, '0' + nr % 10);
2305   if (fileExists(lfi->filename))
2306     return;
2307
2308   // check for Emerald Mine level file (V2 to V5)
2309   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "%d", nr);
2310   if (fileExists(lfi->filename))
2311     return;
2312
2313   // check for Emerald Mine level file (V6 / single mode)
2314   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "%02ds", nr);
2315   if (fileExists(lfi->filename))
2316     return;
2317   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "%02dS", nr);
2318   if (fileExists(lfi->filename))
2319     return;
2320
2321   // check for Emerald Mine level file (V6 / teamwork mode)
2322   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "%02dt", nr);
2323   if (fileExists(lfi->filename))
2324     return;
2325   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_EM, "%02dT", nr);
2326   if (fileExists(lfi->filename))
2327     return;
2328
2329   // check for various packed level file formats
2330   setLevelFileInfo_PackedLevelFilename(lfi, LEVEL_FILE_TYPE_UNKNOWN);
2331   if (fileExists(lfi->filename))
2332     return;
2333
2334   // no known level file found -- use default values (and fail later)
2335   setLevelFileInfo_FormatLevelFilename(lfi, LEVEL_FILE_TYPE_RND,
2336                                        "%03d.%s", nr, LEVELFILE_EXTENSION);
2337 }
2338
2339 static void determineLevelFileInfo_Filetype(struct LevelFileInfo *lfi)
2340 {
2341   if (lfi->type == LEVEL_FILE_TYPE_UNKNOWN)
2342     lfi->type = getFileTypeFromBasename(lfi->basename);
2343
2344   if (lfi->type == LEVEL_FILE_TYPE_RND)
2345     lfi->type = getFileTypeFromMagicBytes(lfi->filename, lfi->type);
2346 }
2347
2348 static void setLevelFileInfo(struct LevelFileInfo *level_file_info, int nr)
2349 {
2350   // always start with reliable default values
2351   setFileInfoToDefaults(level_file_info);
2352
2353   level_file_info->nr = nr;     // set requested level number
2354
2355   determineLevelFileInfo_Filename(level_file_info);
2356   determineLevelFileInfo_Filetype(level_file_info);
2357 }
2358
2359 static void copyLevelFileInfo(struct LevelFileInfo *lfi_from,
2360                               struct LevelFileInfo *lfi_to)
2361 {
2362   lfi_to->nr     = lfi_from->nr;
2363   lfi_to->type   = lfi_from->type;
2364   lfi_to->packed = lfi_from->packed;
2365
2366   setString(&lfi_to->basename, lfi_from->basename);
2367   setString(&lfi_to->filename, lfi_from->filename);
2368 }
2369
2370 // ----------------------------------------------------------------------------
2371 // functions for loading R'n'D level
2372 // ----------------------------------------------------------------------------
2373
2374 int getMappedElement(int element)
2375 {
2376   // remap some (historic, now obsolete) elements
2377
2378   switch (element)
2379   {
2380     case EL_PLAYER_OBSOLETE:
2381       element = EL_PLAYER_1;
2382       break;
2383
2384     case EL_KEY_OBSOLETE:
2385       element = EL_KEY_1;
2386       break;
2387
2388     case EL_EM_KEY_1_FILE_OBSOLETE:
2389       element = EL_EM_KEY_1;
2390       break;
2391
2392     case EL_EM_KEY_2_FILE_OBSOLETE:
2393       element = EL_EM_KEY_2;
2394       break;
2395
2396     case EL_EM_KEY_3_FILE_OBSOLETE:
2397       element = EL_EM_KEY_3;
2398       break;
2399
2400     case EL_EM_KEY_4_FILE_OBSOLETE:
2401       element = EL_EM_KEY_4;
2402       break;
2403
2404     case EL_ENVELOPE_OBSOLETE:
2405       element = EL_ENVELOPE_1;
2406       break;
2407
2408     case EL_SP_EMPTY:
2409       element = EL_EMPTY;
2410       break;
2411
2412     default:
2413       if (element >= NUM_FILE_ELEMENTS)
2414       {
2415         Warn("invalid level element %d", element);
2416
2417         element = EL_UNKNOWN;
2418       }
2419       break;
2420   }
2421
2422   return element;
2423 }
2424
2425 static int getMappedElementByVersion(int element, int game_version)
2426 {
2427   // remap some elements due to certain game version
2428
2429   if (game_version <= VERSION_IDENT(2,2,0,0))
2430   {
2431     // map game font elements
2432     element = (element == EL_CHAR('[')  ? EL_CHAR_AUMLAUT :
2433                element == EL_CHAR('\\') ? EL_CHAR_OUMLAUT :
2434                element == EL_CHAR(']')  ? EL_CHAR_UUMLAUT :
2435                element == EL_CHAR('^')  ? EL_CHAR_COPYRIGHT : element);
2436   }
2437
2438   if (game_version < VERSION_IDENT(3,0,0,0))
2439   {
2440     // map Supaplex gravity tube elements
2441     element = (element == EL_SP_GRAVITY_PORT_LEFT  ? EL_SP_PORT_LEFT  :
2442                element == EL_SP_GRAVITY_PORT_RIGHT ? EL_SP_PORT_RIGHT :
2443                element == EL_SP_GRAVITY_PORT_UP    ? EL_SP_PORT_UP    :
2444                element == EL_SP_GRAVITY_PORT_DOWN  ? EL_SP_PORT_DOWN  :
2445                element);
2446   }
2447
2448   return element;
2449 }
2450
2451 static int LoadLevel_VERS(File *file, int chunk_size, struct LevelInfo *level)
2452 {
2453   level->file_version = getFileVersion(file);
2454   level->game_version = getFileVersion(file);
2455
2456   return chunk_size;
2457 }
2458
2459 static int LoadLevel_DATE(File *file, int chunk_size, struct LevelInfo *level)
2460 {
2461   level->creation_date.year  = getFile16BitBE(file);
2462   level->creation_date.month = getFile8Bit(file);
2463   level->creation_date.day   = getFile8Bit(file);
2464
2465   level->creation_date.src   = DATE_SRC_LEVELFILE;
2466
2467   return chunk_size;
2468 }
2469
2470 static int LoadLevel_HEAD(File *file, int chunk_size, struct LevelInfo *level)
2471 {
2472   int initial_player_stepsize;
2473   int initial_player_gravity;
2474   int i, x, y;
2475
2476   level->fieldx = getFile8Bit(file);
2477   level->fieldy = getFile8Bit(file);
2478
2479   level->time           = getFile16BitBE(file);
2480   level->gems_needed    = getFile16BitBE(file);
2481
2482   for (i = 0; i < MAX_LEVEL_NAME_LEN; i++)
2483     level->name[i] = getFile8Bit(file);
2484   level->name[MAX_LEVEL_NAME_LEN] = 0;
2485
2486   for (i = 0; i < LEVEL_SCORE_ELEMENTS; i++)
2487     level->score[i] = getFile8Bit(file);
2488
2489   level->num_yamyam_contents = STD_ELEMENT_CONTENTS;
2490   for (i = 0; i < STD_ELEMENT_CONTENTS; i++)
2491     for (y = 0; y < 3; y++)
2492       for (x = 0; x < 3; x++)
2493         level->yamyam_content[i].e[x][y] = getMappedElement(getFile8Bit(file));
2494
2495   level->amoeba_speed           = getFile8Bit(file);
2496   level->time_magic_wall        = getFile8Bit(file);
2497   level->time_wheel             = getFile8Bit(file);
2498   level->amoeba_content         = getMappedElement(getFile8Bit(file));
2499
2500   initial_player_stepsize       = (getFile8Bit(file) == 1 ? STEPSIZE_FAST :
2501                                    STEPSIZE_NORMAL);
2502
2503   for (i = 0; i < MAX_PLAYERS; i++)
2504     level->initial_player_stepsize[i] = initial_player_stepsize;
2505
2506   initial_player_gravity        = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2507
2508   for (i = 0; i < MAX_PLAYERS; i++)
2509     level->initial_player_gravity[i] = initial_player_gravity;
2510
2511   level->encoding_16bit_field   = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2512   level->em_slippery_gems       = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2513
2514   level->use_custom_template    = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2515
2516   level->block_last_field       = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2517   level->sp_block_last_field    = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2518   level->can_move_into_acid_bits = getFile32BitBE(file);
2519   level->dont_collide_with_bits = getFile8Bit(file);
2520
2521   level->use_spring_bug         = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2522   level->use_step_counter       = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2523
2524   level->instant_relocation     = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2525   level->can_pass_to_walkable   = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2526   level->grow_into_diggable     = (getFile8Bit(file) == 1 ? TRUE : FALSE);
2527
2528   level->game_engine_type       = getFile8Bit(file);
2529
2530   ReadUnusedBytesFromFile(file, LEVEL_CHUNK_HEAD_UNUSED);
2531
2532   return chunk_size;
2533 }
2534
2535 static int LoadLevel_NAME(File *file, int chunk_size, struct LevelInfo *level)
2536 {
2537   int i;
2538
2539   for (i = 0; i < MAX_LEVEL_NAME_LEN; i++)
2540     level->name[i] = getFile8Bit(file);
2541   level->name[MAX_LEVEL_NAME_LEN] = 0;
2542
2543   return chunk_size;
2544 }
2545
2546 static int LoadLevel_AUTH(File *file, int chunk_size, struct LevelInfo *level)
2547 {
2548   int i;
2549
2550   for (i = 0; i < MAX_LEVEL_AUTHOR_LEN; i++)
2551     level->author[i] = getFile8Bit(file);
2552   level->author[MAX_LEVEL_AUTHOR_LEN] = 0;
2553
2554   return chunk_size;
2555 }
2556
2557 static int LoadLevel_BODY(File *file, int chunk_size, struct LevelInfo *level)
2558 {
2559   int x, y;
2560   int chunk_size_expected = level->fieldx * level->fieldy;
2561
2562   /* Note: "chunk_size" was wrong before version 2.0 when elements are
2563      stored with 16-bit encoding (and should be twice as big then).
2564      Even worse, playfield data was stored 16-bit when only yamyam content
2565      contained 16-bit elements and vice versa. */
2566
2567   if (level->encoding_16bit_field && level->file_version >= FILE_VERSION_2_0)
2568     chunk_size_expected *= 2;
2569
2570   if (chunk_size_expected != chunk_size)
2571   {
2572     ReadUnusedBytesFromFile(file, chunk_size);
2573     return chunk_size_expected;
2574   }
2575
2576   for (y = 0; y < level->fieldy; y++)
2577     for (x = 0; x < level->fieldx; x++)
2578       level->field[x][y] =
2579         getMappedElement(level->encoding_16bit_field ? getFile16BitBE(file) :
2580                          getFile8Bit(file));
2581   return chunk_size;
2582 }
2583
2584 static int LoadLevel_CONT(File *file, int chunk_size, struct LevelInfo *level)
2585 {
2586   int i, x, y;
2587   int header_size = 4;
2588   int content_size = MAX_ELEMENT_CONTENTS * 3 * 3;
2589   int chunk_size_expected = header_size + content_size;
2590
2591   /* Note: "chunk_size" was wrong before version 2.0 when elements are
2592      stored with 16-bit encoding (and should be twice as big then).
2593      Even worse, playfield data was stored 16-bit when only yamyam content
2594      contained 16-bit elements and vice versa. */
2595
2596   if (level->encoding_16bit_field && level->file_version >= FILE_VERSION_2_0)
2597     chunk_size_expected += content_size;
2598
2599   if (chunk_size_expected != chunk_size)
2600   {
2601     ReadUnusedBytesFromFile(file, chunk_size);
2602     return chunk_size_expected;
2603   }
2604
2605   getFile8Bit(file);
2606   level->num_yamyam_contents = getFile8Bit(file);
2607   getFile8Bit(file);
2608   getFile8Bit(file);
2609
2610   // correct invalid number of content fields -- should never happen
2611   if (level->num_yamyam_contents < 1 ||
2612       level->num_yamyam_contents > MAX_ELEMENT_CONTENTS)
2613     level->num_yamyam_contents = STD_ELEMENT_CONTENTS;
2614
2615   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
2616     for (y = 0; y < 3; y++)
2617       for (x = 0; x < 3; x++)
2618         level->yamyam_content[i].e[x][y] =
2619           getMappedElement(level->encoding_16bit_field ?
2620                            getFile16BitBE(file) : getFile8Bit(file));
2621   return chunk_size;
2622 }
2623
2624 static int LoadLevel_CNT2(File *file, int chunk_size, struct LevelInfo *level)
2625 {
2626   int i, x, y;
2627   int element;
2628   int num_contents;
2629   int content_array[MAX_ELEMENT_CONTENTS][3][3];
2630
2631   element = getMappedElement(getFile16BitBE(file));
2632   num_contents = getFile8Bit(file);
2633
2634   getFile8Bit(file);    // content x size (unused)
2635   getFile8Bit(file);    // content y size (unused)
2636
2637   ReadUnusedBytesFromFile(file, LEVEL_CHUNK_CNT2_UNUSED);
2638
2639   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
2640     for (y = 0; y < 3; y++)
2641       for (x = 0; x < 3; x++)
2642         content_array[i][x][y] = getMappedElement(getFile16BitBE(file));
2643
2644   // correct invalid number of content fields -- should never happen
2645   if (num_contents < 1 || num_contents > MAX_ELEMENT_CONTENTS)
2646     num_contents = STD_ELEMENT_CONTENTS;
2647
2648   if (element == EL_YAMYAM)
2649   {
2650     level->num_yamyam_contents = num_contents;
2651
2652     for (i = 0; i < num_contents; i++)
2653       for (y = 0; y < 3; y++)
2654         for (x = 0; x < 3; x++)
2655           level->yamyam_content[i].e[x][y] = content_array[i][x][y];
2656   }
2657   else if (element == EL_BD_AMOEBA)
2658   {
2659     level->amoeba_content = content_array[0][0][0];
2660   }
2661   else
2662   {
2663     Warn("cannot load content for element '%d'", element);
2664   }
2665
2666   return chunk_size;
2667 }
2668
2669 static int LoadLevel_CNT3(File *file, int chunk_size, struct LevelInfo *level)
2670 {
2671   int i;
2672   int element;
2673   int envelope_nr;
2674   int envelope_len;
2675   int chunk_size_expected;
2676
2677   element = getMappedElement(getFile16BitBE(file));
2678   if (!IS_ENVELOPE(element))
2679     element = EL_ENVELOPE_1;
2680
2681   envelope_nr = element - EL_ENVELOPE_1;
2682
2683   envelope_len = getFile16BitBE(file);
2684
2685   level->envelope[envelope_nr].xsize = getFile8Bit(file);
2686   level->envelope[envelope_nr].ysize = getFile8Bit(file);
2687
2688   ReadUnusedBytesFromFile(file, LEVEL_CHUNK_CNT3_UNUSED);
2689
2690   chunk_size_expected = LEVEL_CHUNK_CNT3_SIZE(envelope_len);
2691   if (chunk_size_expected != chunk_size)
2692   {
2693     ReadUnusedBytesFromFile(file, chunk_size - LEVEL_CHUNK_CNT3_HEADER);
2694     return chunk_size_expected;
2695   }
2696
2697   for (i = 0; i < envelope_len; i++)
2698     level->envelope[envelope_nr].text[i] = getFile8Bit(file);
2699
2700   return chunk_size;
2701 }
2702
2703 static int LoadLevel_CUS1(File *file, int chunk_size, struct LevelInfo *level)
2704 {
2705   int num_changed_custom_elements = getFile16BitBE(file);
2706   int chunk_size_expected = 2 + num_changed_custom_elements * 6;
2707   int i;
2708
2709   if (chunk_size_expected != chunk_size)
2710   {
2711     ReadUnusedBytesFromFile(file, chunk_size - 2);
2712     return chunk_size_expected;
2713   }
2714
2715   for (i = 0; i < num_changed_custom_elements; i++)
2716   {
2717     int element = getMappedElement(getFile16BitBE(file));
2718     int properties = getFile32BitBE(file);
2719
2720     if (IS_CUSTOM_ELEMENT(element))
2721       element_info[element].properties[EP_BITFIELD_BASE_NR] = properties;
2722     else
2723       Warn("invalid custom element number %d", element);
2724
2725     // older game versions that wrote level files with CUS1 chunks used
2726     // different default push delay values (not yet stored in level file)
2727     element_info[element].push_delay_fixed = 2;
2728     element_info[element].push_delay_random = 8;
2729   }
2730
2731   level->file_has_custom_elements = TRUE;
2732
2733   return chunk_size;
2734 }
2735
2736 static int LoadLevel_CUS2(File *file, int chunk_size, struct LevelInfo *level)
2737 {
2738   int num_changed_custom_elements = getFile16BitBE(file);
2739   int chunk_size_expected = 2 + num_changed_custom_elements * 4;
2740   int i;
2741
2742   if (chunk_size_expected != chunk_size)
2743   {
2744     ReadUnusedBytesFromFile(file, chunk_size - 2);
2745     return chunk_size_expected;
2746   }
2747
2748   for (i = 0; i < num_changed_custom_elements; i++)
2749   {
2750     int element = getMappedElement(getFile16BitBE(file));
2751     int custom_target_element = getMappedElement(getFile16BitBE(file));
2752
2753     if (IS_CUSTOM_ELEMENT(element))
2754       element_info[element].change->target_element = custom_target_element;
2755     else
2756       Warn("invalid custom element number %d", element);
2757   }
2758
2759   level->file_has_custom_elements = TRUE;
2760
2761   return chunk_size;
2762 }
2763
2764 static int LoadLevel_CUS3(File *file, int chunk_size, struct LevelInfo *level)
2765 {
2766   int num_changed_custom_elements = getFile16BitBE(file);
2767   int chunk_size_expected = LEVEL_CHUNK_CUS3_SIZE(num_changed_custom_elements);
2768   int i, j, x, y;
2769
2770   if (chunk_size_expected != chunk_size)
2771   {
2772     ReadUnusedBytesFromFile(file, chunk_size - 2);
2773     return chunk_size_expected;
2774   }
2775
2776   for (i = 0; i < num_changed_custom_elements; i++)
2777   {
2778     int element = getMappedElement(getFile16BitBE(file));
2779     struct ElementInfo *ei = &element_info[element];
2780     unsigned int event_bits;
2781
2782     if (!IS_CUSTOM_ELEMENT(element))
2783     {
2784       Warn("invalid custom element number %d", element);
2785
2786       element = EL_INTERNAL_DUMMY;
2787     }
2788
2789     for (j = 0; j < MAX_ELEMENT_NAME_LEN; j++)
2790       ei->description[j] = getFile8Bit(file);
2791     ei->description[MAX_ELEMENT_NAME_LEN] = 0;
2792
2793     ei->properties[EP_BITFIELD_BASE_NR] = getFile32BitBE(file);
2794
2795     // some free bytes for future properties and padding
2796     ReadUnusedBytesFromFile(file, 7);
2797
2798     ei->use_gfx_element = getFile8Bit(file);
2799     ei->gfx_element_initial = getMappedElement(getFile16BitBE(file));
2800
2801     ei->collect_score_initial = getFile8Bit(file);
2802     ei->collect_count_initial = getFile8Bit(file);
2803
2804     ei->push_delay_fixed = getFile16BitBE(file);
2805     ei->push_delay_random = getFile16BitBE(file);
2806     ei->move_delay_fixed = getFile16BitBE(file);
2807     ei->move_delay_random = getFile16BitBE(file);
2808
2809     ei->move_pattern = getFile16BitBE(file);
2810     ei->move_direction_initial = getFile8Bit(file);
2811     ei->move_stepsize = getFile8Bit(file);
2812
2813     for (y = 0; y < 3; y++)
2814       for (x = 0; x < 3; x++)
2815         ei->content.e[x][y] = getMappedElement(getFile16BitBE(file));
2816
2817     event_bits = getFile32BitBE(file);
2818     for (j = 0; j < NUM_CHANGE_EVENTS; j++)
2819       if (event_bits & (1 << j))
2820         ei->change->has_event[j] = TRUE;
2821
2822     ei->change->target_element = getMappedElement(getFile16BitBE(file));
2823
2824     ei->change->delay_fixed = getFile16BitBE(file);
2825     ei->change->delay_random = getFile16BitBE(file);
2826     ei->change->delay_frames = getFile16BitBE(file);
2827
2828     ei->change->initial_trigger_element= getMappedElement(getFile16BitBE(file));
2829
2830     ei->change->explode = getFile8Bit(file);
2831     ei->change->use_target_content = getFile8Bit(file);
2832     ei->change->only_if_complete = getFile8Bit(file);
2833     ei->change->use_random_replace = getFile8Bit(file);
2834
2835     ei->change->random_percentage = getFile8Bit(file);
2836     ei->change->replace_when = getFile8Bit(file);
2837
2838     for (y = 0; y < 3; y++)
2839       for (x = 0; x < 3; x++)
2840         ei->change->target_content.e[x][y] =
2841           getMappedElement(getFile16BitBE(file));
2842
2843     ei->slippery_type = getFile8Bit(file);
2844
2845     // some free bytes for future properties and padding
2846     ReadUnusedBytesFromFile(file, LEVEL_CPART_CUS3_UNUSED);
2847
2848     // mark that this custom element has been modified
2849     ei->modified_settings = TRUE;
2850   }
2851
2852   level->file_has_custom_elements = TRUE;
2853
2854   return chunk_size;
2855 }
2856
2857 static int LoadLevel_CUS4(File *file, int chunk_size, struct LevelInfo *level)
2858 {
2859   struct ElementInfo *ei;
2860   int chunk_size_expected;
2861   int element;
2862   int i, j, x, y;
2863
2864   // ---------- custom element base property values (96 bytes) ----------------
2865
2866   element = getMappedElement(getFile16BitBE(file));
2867
2868   if (!IS_CUSTOM_ELEMENT(element))
2869   {
2870     Warn("invalid custom element number %d", element);
2871
2872     ReadUnusedBytesFromFile(file, chunk_size - 2);
2873
2874     return chunk_size;
2875   }
2876
2877   ei = &element_info[element];
2878
2879   for (i = 0; i < MAX_ELEMENT_NAME_LEN; i++)
2880     ei->description[i] = getFile8Bit(file);
2881   ei->description[MAX_ELEMENT_NAME_LEN] = 0;
2882
2883   ei->properties[EP_BITFIELD_BASE_NR] = getFile32BitBE(file);
2884
2885   ReadUnusedBytesFromFile(file, 4);     // reserved for more base properties
2886
2887   ei->num_change_pages = getFile8Bit(file);
2888
2889   chunk_size_expected = LEVEL_CHUNK_CUS4_SIZE(ei->num_change_pages);
2890   if (chunk_size_expected != chunk_size)
2891   {
2892     ReadUnusedBytesFromFile(file, chunk_size - 43);
2893     return chunk_size_expected;
2894   }
2895
2896   ei->ce_value_fixed_initial = getFile16BitBE(file);
2897   ei->ce_value_random_initial = getFile16BitBE(file);
2898   ei->use_last_ce_value = getFile8Bit(file);
2899
2900   ei->use_gfx_element = getFile8Bit(file);
2901   ei->gfx_element_initial = getMappedElement(getFile16BitBE(file));
2902
2903   ei->collect_score_initial = getFile8Bit(file);
2904   ei->collect_count_initial = getFile8Bit(file);
2905
2906   ei->drop_delay_fixed = getFile8Bit(file);
2907   ei->push_delay_fixed = getFile8Bit(file);
2908   ei->drop_delay_random = getFile8Bit(file);
2909   ei->push_delay_random = getFile8Bit(file);
2910   ei->move_delay_fixed = getFile16BitBE(file);
2911   ei->move_delay_random = getFile16BitBE(file);
2912
2913   // bits 0 - 15 of "move_pattern" ...
2914   ei->move_pattern = getFile16BitBE(file);
2915   ei->move_direction_initial = getFile8Bit(file);
2916   ei->move_stepsize = getFile8Bit(file);
2917
2918   ei->slippery_type = getFile8Bit(file);
2919
2920   for (y = 0; y < 3; y++)
2921     for (x = 0; x < 3; x++)
2922       ei->content.e[x][y] = getMappedElement(getFile16BitBE(file));
2923
2924   ei->move_enter_element = getMappedElement(getFile16BitBE(file));
2925   ei->move_leave_element = getMappedElement(getFile16BitBE(file));
2926   ei->move_leave_type = getFile8Bit(file);
2927
2928   // ... bits 16 - 31 of "move_pattern" (not nice, but downward compatible)
2929   ei->move_pattern |= (getFile16BitBE(file) << 16);
2930
2931   ei->access_direction = getFile8Bit(file);
2932
2933   ei->explosion_delay = getFile8Bit(file);
2934   ei->ignition_delay = getFile8Bit(file);
2935   ei->explosion_type = getFile8Bit(file);
2936
2937   // some free bytes for future custom property values and padding
2938   ReadUnusedBytesFromFile(file, 1);
2939
2940   // ---------- change page property values (48 bytes) ------------------------
2941
2942   setElementChangePages(ei, ei->num_change_pages);
2943
2944   for (i = 0; i < ei->num_change_pages; i++)
2945   {
2946     struct ElementChangeInfo *change = &ei->change_page[i];
2947     unsigned int event_bits;
2948
2949     // always start with reliable default values
2950     setElementChangeInfoToDefaults(change);
2951
2952     // bits 0 - 31 of "has_event[]" ...
2953     event_bits = getFile32BitBE(file);
2954     for (j = 0; j < MIN(NUM_CHANGE_EVENTS, 32); j++)
2955       if (event_bits & (1 << j))
2956         change->has_event[j] = TRUE;
2957
2958     change->target_element = getMappedElement(getFile16BitBE(file));
2959
2960     change->delay_fixed = getFile16BitBE(file);
2961     change->delay_random = getFile16BitBE(file);
2962     change->delay_frames = getFile16BitBE(file);
2963
2964     change->initial_trigger_element = getMappedElement(getFile16BitBE(file));
2965
2966     change->explode = getFile8Bit(file);
2967     change->use_target_content = getFile8Bit(file);
2968     change->only_if_complete = getFile8Bit(file);
2969     change->use_random_replace = getFile8Bit(file);
2970
2971     change->random_percentage = getFile8Bit(file);
2972     change->replace_when = getFile8Bit(file);
2973
2974     for (y = 0; y < 3; y++)
2975       for (x = 0; x < 3; x++)
2976         change->target_content.e[x][y]= getMappedElement(getFile16BitBE(file));
2977
2978     change->can_change = getFile8Bit(file);
2979
2980     change->trigger_side = getFile8Bit(file);
2981
2982     change->trigger_player = getFile8Bit(file);
2983     change->trigger_page = getFile8Bit(file);
2984
2985     change->trigger_page = (change->trigger_page == CH_PAGE_ANY_FILE ?
2986                             CH_PAGE_ANY : (1 << change->trigger_page));
2987
2988     change->has_action = getFile8Bit(file);
2989     change->action_type = getFile8Bit(file);
2990     change->action_mode = getFile8Bit(file);
2991     change->action_arg = getFile16BitBE(file);
2992
2993     // ... bits 32 - 39 of "has_event[]" (not nice, but downward compatible)
2994     event_bits = getFile8Bit(file);
2995     for (j = 32; j < NUM_CHANGE_EVENTS; j++)
2996       if (event_bits & (1 << (j - 32)))
2997         change->has_event[j] = TRUE;
2998   }
2999
3000   // mark this custom element as modified
3001   ei->modified_settings = TRUE;
3002
3003   level->file_has_custom_elements = TRUE;
3004
3005   return chunk_size;
3006 }
3007
3008 static int LoadLevel_GRP1(File *file, int chunk_size, struct LevelInfo *level)
3009 {
3010   struct ElementInfo *ei;
3011   struct ElementGroupInfo *group;
3012   int element;
3013   int i;
3014
3015   element = getMappedElement(getFile16BitBE(file));
3016
3017   if (!IS_GROUP_ELEMENT(element))
3018   {
3019     Warn("invalid group element number %d", element);
3020
3021     ReadUnusedBytesFromFile(file, chunk_size - 2);
3022
3023     return chunk_size;
3024   }
3025
3026   ei = &element_info[element];
3027
3028   for (i = 0; i < MAX_ELEMENT_NAME_LEN; i++)
3029     ei->description[i] = getFile8Bit(file);
3030   ei->description[MAX_ELEMENT_NAME_LEN] = 0;
3031
3032   group = element_info[element].group;
3033
3034   group->num_elements = getFile8Bit(file);
3035
3036   ei->use_gfx_element = getFile8Bit(file);
3037   ei->gfx_element_initial = getMappedElement(getFile16BitBE(file));
3038
3039   group->choice_mode = getFile8Bit(file);
3040
3041   // some free bytes for future values and padding
3042   ReadUnusedBytesFromFile(file, 3);
3043
3044   for (i = 0; i < MAX_ELEMENTS_IN_GROUP; i++)
3045     group->element[i] = getMappedElement(getFile16BitBE(file));
3046
3047   // mark this group element as modified
3048   element_info[element].modified_settings = TRUE;
3049
3050   level->file_has_custom_elements = TRUE;
3051
3052   return chunk_size;
3053 }
3054
3055 static int LoadLevel_MicroChunk(File *file, struct LevelFileConfigInfo *conf,
3056                                 int element, int real_element)
3057 {
3058   int micro_chunk_size = 0;
3059   int conf_type = getFile8Bit(file);
3060   int byte_mask = conf_type & CONF_MASK_BYTES;
3061   boolean element_found = FALSE;
3062   int i;
3063
3064   micro_chunk_size += 1;
3065
3066   if (byte_mask == CONF_MASK_MULTI_BYTES)
3067   {
3068     int num_bytes = getFile16BitBE(file);
3069     byte *buffer = checked_malloc(num_bytes);
3070
3071     ReadBytesFromFile(file, buffer, num_bytes);
3072
3073     for (i = 0; conf[i].data_type != -1; i++)
3074     {
3075       if (conf[i].element == element &&
3076           conf[i].conf_type == conf_type)
3077       {
3078         int data_type = conf[i].data_type;
3079         int num_entities = num_bytes / CONF_ENTITY_NUM_BYTES(data_type);
3080         int max_num_entities = conf[i].max_num_entities;
3081
3082         if (num_entities > max_num_entities)
3083         {
3084           Warn("truncating number of entities for element %d from %d to %d",
3085                element, num_entities, max_num_entities);
3086
3087           num_entities = max_num_entities;
3088         }
3089
3090         if (num_entities == 0 && (data_type == TYPE_ELEMENT_LIST ||
3091                                   data_type == TYPE_CONTENT_LIST))
3092         {
3093           // for element and content lists, zero entities are not allowed
3094           Warn("found empty list of entities for element %d", element);
3095
3096           // do not set "num_entities" here to prevent reading behind buffer
3097
3098           *(int *)(conf[i].num_entities) = 1;   // at least one is required
3099         }
3100         else
3101         {
3102           *(int *)(conf[i].num_entities) = num_entities;
3103         }
3104
3105         element_found = TRUE;
3106
3107         if (data_type == TYPE_STRING)
3108         {
3109           char *string = (char *)(conf[i].value);
3110           int j;
3111
3112           for (j = 0; j < max_num_entities; j++)
3113             string[j] = (j < num_entities ? buffer[j] : '\0');
3114         }
3115         else if (data_type == TYPE_ELEMENT_LIST)
3116         {
3117           int *element_array = (int *)(conf[i].value);
3118           int j;
3119
3120           for (j = 0; j < num_entities; j++)
3121             element_array[j] =
3122               getMappedElement(CONF_ELEMENTS_ELEMENT(buffer, j));
3123         }
3124         else if (data_type == TYPE_CONTENT_LIST)
3125         {
3126           struct Content *content= (struct Content *)(conf[i].value);
3127           int c, x, y;
3128
3129           for (c = 0; c < num_entities; c++)
3130             for (y = 0; y < 3; y++)
3131               for (x = 0; x < 3; x++)
3132                 content[c].e[x][y] =
3133                   getMappedElement(CONF_CONTENTS_ELEMENT(buffer, c, x, y));
3134         }
3135         else
3136           element_found = FALSE;
3137
3138         break;
3139       }
3140     }
3141
3142     checked_free(buffer);
3143
3144     micro_chunk_size += 2 + num_bytes;
3145   }
3146   else          // constant size configuration data (1, 2 or 4 bytes)
3147   {
3148     int value = (byte_mask == CONF_MASK_1_BYTE ? getFile8Bit   (file) :
3149                  byte_mask == CONF_MASK_2_BYTE ? getFile16BitBE(file) :
3150                  byte_mask == CONF_MASK_4_BYTE ? getFile32BitBE(file) : 0);
3151
3152     for (i = 0; conf[i].data_type != -1; i++)
3153     {
3154       if (conf[i].element == element &&
3155           conf[i].conf_type == conf_type)
3156       {
3157         int data_type = conf[i].data_type;
3158
3159         if (data_type == TYPE_ELEMENT)
3160           value = getMappedElement(value);
3161
3162         if (data_type == TYPE_BOOLEAN)
3163           *(boolean *)(conf[i].value) = value;
3164         else
3165           *(int *)    (conf[i].value) = value;
3166
3167         element_found = TRUE;
3168
3169         break;
3170       }
3171     }
3172
3173     micro_chunk_size += CONF_VALUE_NUM_BYTES(byte_mask);
3174   }
3175
3176   if (!element_found)
3177   {
3178     char *error_conf_chunk_bytes =
3179       (byte_mask == CONF_MASK_1_BYTE ? "CONF_VALUE_8_BIT" :
3180        byte_mask == CONF_MASK_2_BYTE ? "CONF_VALUE_16_BIT" :
3181        byte_mask == CONF_MASK_4_BYTE ? "CONF_VALUE_32_BIT" :"CONF_VALUE_BYTES");
3182     int error_conf_chunk_token = conf_type & CONF_MASK_TOKEN;
3183     int error_element = real_element;
3184
3185     Warn("cannot load micro chunk '%s(%d)' value for element %d ['%s']",
3186          error_conf_chunk_bytes, error_conf_chunk_token,
3187          error_element, EL_NAME(error_element));
3188   }
3189
3190   return micro_chunk_size;
3191 }
3192
3193 static int LoadLevel_INFO(File *file, int chunk_size, struct LevelInfo *level)
3194 {
3195   int real_chunk_size = 0;
3196
3197   li = *level;          // copy level data into temporary buffer
3198
3199   while (!checkEndOfFile(file))
3200   {
3201     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_INFO, -1, -1);
3202
3203     if (real_chunk_size >= chunk_size)
3204       break;
3205   }
3206
3207   *level = li;          // copy temporary buffer back to level data
3208
3209   return real_chunk_size;
3210 }
3211
3212 static int LoadLevel_CONF(File *file, int chunk_size, struct LevelInfo *level)
3213 {
3214   int real_chunk_size = 0;
3215
3216   li = *level;          // copy level data into temporary buffer
3217
3218   while (!checkEndOfFile(file))
3219   {
3220     int element = getMappedElement(getFile16BitBE(file));
3221
3222     real_chunk_size += 2;
3223     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_CONF,
3224                                             element, element);
3225     if (real_chunk_size >= chunk_size)
3226       break;
3227   }
3228
3229   *level = li;          // copy temporary buffer back to level data
3230
3231   return real_chunk_size;
3232 }
3233
3234 static int LoadLevel_ELEM(File *file, int chunk_size, struct LevelInfo *level)
3235 {
3236   int real_chunk_size = 0;
3237
3238   li = *level;          // copy level data into temporary buffer
3239
3240   while (!checkEndOfFile(file))
3241   {
3242     int element = getMappedElement(getFile16BitBE(file));
3243
3244     real_chunk_size += 2;
3245     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_ELEM,
3246                                             element, element);
3247     if (real_chunk_size >= chunk_size)
3248       break;
3249   }
3250
3251   *level = li;          // copy temporary buffer back to level data
3252
3253   return real_chunk_size;
3254 }
3255
3256 static int LoadLevel_NOTE(File *file, int chunk_size, struct LevelInfo *level)
3257 {
3258   int element = getMappedElement(getFile16BitBE(file));
3259   int envelope_nr = element - EL_ENVELOPE_1;
3260   int real_chunk_size = 2;
3261
3262   xx_envelope = level->envelope[envelope_nr];   // copy into temporary buffer
3263
3264   while (!checkEndOfFile(file))
3265   {
3266     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_NOTE,
3267                                             -1, element);
3268
3269     if (real_chunk_size >= chunk_size)
3270       break;
3271   }
3272
3273   level->envelope[envelope_nr] = xx_envelope;   // copy from temporary buffer
3274
3275   return real_chunk_size;
3276 }
3277
3278 static int LoadLevel_CUSX(File *file, int chunk_size, struct LevelInfo *level)
3279 {
3280   int element = getMappedElement(getFile16BitBE(file));
3281   int real_chunk_size = 2;
3282   struct ElementInfo *ei = &element_info[element];
3283   int i;
3284
3285   xx_ei = *ei;          // copy element data into temporary buffer
3286
3287   xx_ei.num_change_pages = -1;
3288
3289   while (!checkEndOfFile(file))
3290   {
3291     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_CUSX_base,
3292                                             -1, element);
3293     if (xx_ei.num_change_pages != -1)
3294       break;
3295
3296     if (real_chunk_size >= chunk_size)
3297       break;
3298   }
3299
3300   *ei = xx_ei;
3301
3302   if (ei->num_change_pages == -1)
3303   {
3304     Warn("LoadLevel_CUSX(): missing 'num_change_pages' for '%s'",
3305          EL_NAME(element));
3306
3307     ei->num_change_pages = 1;
3308
3309     setElementChangePages(ei, 1);
3310     setElementChangeInfoToDefaults(ei->change);
3311
3312     return real_chunk_size;
3313   }
3314
3315   // initialize number of change pages stored for this custom element
3316   setElementChangePages(ei, ei->num_change_pages);
3317   for (i = 0; i < ei->num_change_pages; i++)
3318     setElementChangeInfoToDefaults(&ei->change_page[i]);
3319
3320   // start with reading properties for the first change page
3321   xx_current_change_page = 0;
3322
3323   while (!checkEndOfFile(file))
3324   {
3325     struct ElementChangeInfo *change = &ei->change_page[xx_current_change_page];
3326
3327     xx_change = *change;        // copy change data into temporary buffer
3328
3329     resetEventBits();           // reset bits; change page might have changed
3330
3331     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_CUSX_change,
3332                                             -1, element);
3333
3334     *change = xx_change;
3335
3336     setEventFlagsFromEventBits(change);
3337
3338     if (real_chunk_size >= chunk_size)
3339       break;
3340   }
3341
3342   level->file_has_custom_elements = TRUE;
3343
3344   return real_chunk_size;
3345 }
3346
3347 static int LoadLevel_GRPX(File *file, int chunk_size, struct LevelInfo *level)
3348 {
3349   int element = getMappedElement(getFile16BitBE(file));
3350   int real_chunk_size = 2;
3351   struct ElementInfo *ei = &element_info[element];
3352   struct ElementGroupInfo *group = ei->group;
3353
3354   xx_ei = *ei;          // copy element data into temporary buffer
3355   xx_group = *group;    // copy group data into temporary buffer
3356
3357   while (!checkEndOfFile(file))
3358   {
3359     real_chunk_size += LoadLevel_MicroChunk(file, chunk_config_GRPX,
3360                                             -1, element);
3361
3362     if (real_chunk_size >= chunk_size)
3363       break;
3364   }
3365
3366   *ei = xx_ei;
3367   *group = xx_group;
3368
3369   level->file_has_custom_elements = TRUE;
3370
3371   return real_chunk_size;
3372 }
3373
3374 static void LoadLevelFromFileInfo_RND(struct LevelInfo *level,
3375                                       struct LevelFileInfo *level_file_info,
3376                                       boolean level_info_only)
3377 {
3378   char *filename = level_file_info->filename;
3379   char cookie[MAX_LINE_LEN];
3380   char chunk_name[CHUNK_ID_LEN + 1];
3381   int chunk_size;
3382   File *file;
3383
3384   if (!(file = openFile(filename, MODE_READ)))
3385   {
3386     level->no_valid_file = TRUE;
3387     level->no_level_file = TRUE;
3388
3389     if (level_info_only)
3390       return;
3391
3392     Warn("cannot read level '%s' -- using empty level", filename);
3393
3394     if (!setup.editor.use_template_for_new_levels)
3395       return;
3396
3397     // if level file not found, try to initialize level data from template
3398     filename = getGlobalLevelTemplateFilename();
3399
3400     if (!(file = openFile(filename, MODE_READ)))
3401       return;
3402
3403     // default: for empty levels, use level template for custom elements
3404     level->use_custom_template = TRUE;
3405
3406     level->no_valid_file = FALSE;
3407   }
3408
3409   getFileChunkBE(file, chunk_name, NULL);
3410   if (strEqual(chunk_name, "RND1"))
3411   {
3412     getFile32BitBE(file);               // not used
3413
3414     getFileChunkBE(file, chunk_name, NULL);
3415     if (!strEqual(chunk_name, "CAVE"))
3416     {
3417       level->no_valid_file = TRUE;
3418
3419       Warn("unknown format of level file '%s'", filename);
3420
3421       closeFile(file);
3422
3423       return;
3424     }
3425   }
3426   else  // check for pre-2.0 file format with cookie string
3427   {
3428     strcpy(cookie, chunk_name);
3429     if (getStringFromFile(file, &cookie[4], MAX_LINE_LEN - 4) == NULL)
3430       cookie[4] = '\0';
3431     if (strlen(cookie) > 0 && cookie[strlen(cookie) - 1] == '\n')
3432       cookie[strlen(cookie) - 1] = '\0';
3433
3434     if (!checkCookieString(cookie, LEVEL_COOKIE_TMPL))
3435     {
3436       level->no_valid_file = TRUE;
3437
3438       Warn("unknown format of level file '%s'", filename);
3439
3440       closeFile(file);
3441
3442       return;
3443     }
3444
3445     if ((level->file_version = getFileVersionFromCookieString(cookie)) == -1)
3446     {
3447       level->no_valid_file = TRUE;
3448
3449       Warn("unsupported version of level file '%s'", filename);
3450
3451       closeFile(file);
3452
3453       return;
3454     }
3455
3456     // pre-2.0 level files have no game version, so use file version here
3457     level->game_version = level->file_version;
3458   }
3459
3460   if (level->file_version < FILE_VERSION_1_2)
3461   {
3462     // level files from versions before 1.2.0 without chunk structure
3463     LoadLevel_HEAD(file, LEVEL_CHUNK_HEAD_SIZE,         level);
3464     LoadLevel_BODY(file, level->fieldx * level->fieldy, level);
3465   }
3466   else
3467   {
3468     static struct
3469     {
3470       char *name;
3471       int size;
3472       int (*loader)(File *, int, struct LevelInfo *);
3473     }
3474     chunk_info[] =
3475     {
3476       { "VERS", LEVEL_CHUNK_VERS_SIZE,  LoadLevel_VERS },
3477       { "DATE", LEVEL_CHUNK_DATE_SIZE,  LoadLevel_DATE },
3478       { "HEAD", LEVEL_CHUNK_HEAD_SIZE,  LoadLevel_HEAD },
3479       { "NAME", LEVEL_CHUNK_NAME_SIZE,  LoadLevel_NAME },
3480       { "AUTH", LEVEL_CHUNK_AUTH_SIZE,  LoadLevel_AUTH },
3481       { "INFO", -1,                     LoadLevel_INFO },
3482       { "BODY", -1,                     LoadLevel_BODY },
3483       { "CONT", -1,                     LoadLevel_CONT },
3484       { "CNT2", LEVEL_CHUNK_CNT2_SIZE,  LoadLevel_CNT2 },
3485       { "CNT3", -1,                     LoadLevel_CNT3 },
3486       { "CUS1", -1,                     LoadLevel_CUS1 },
3487       { "CUS2", -1,                     LoadLevel_CUS2 },
3488       { "CUS3", -1,                     LoadLevel_CUS3 },
3489       { "CUS4", -1,                     LoadLevel_CUS4 },
3490       { "GRP1", -1,                     LoadLevel_GRP1 },
3491       { "CONF", -1,                     LoadLevel_CONF },
3492       { "ELEM", -1,                     LoadLevel_ELEM },
3493       { "NOTE", -1,                     LoadLevel_NOTE },
3494       { "CUSX", -1,                     LoadLevel_CUSX },
3495       { "GRPX", -1,                     LoadLevel_GRPX },
3496
3497       {  NULL,  0,                      NULL }
3498     };
3499
3500     while (getFileChunkBE(file, chunk_name, &chunk_size))
3501     {
3502       int i = 0;
3503
3504       while (chunk_info[i].name != NULL &&
3505              !strEqual(chunk_name, chunk_info[i].name))
3506         i++;
3507
3508       if (chunk_info[i].name == NULL)
3509       {
3510         Warn("unknown chunk '%s' in level file '%s'",
3511              chunk_name, filename);
3512
3513         ReadUnusedBytesFromFile(file, chunk_size);
3514       }
3515       else if (chunk_info[i].size != -1 &&
3516                chunk_info[i].size != chunk_size)
3517       {
3518         Warn("wrong size (%d) of chunk '%s' in level file '%s'",
3519              chunk_size, chunk_name, filename);
3520
3521         ReadUnusedBytesFromFile(file, chunk_size);
3522       }
3523       else
3524       {
3525         // call function to load this level chunk
3526         int chunk_size_expected =
3527           (chunk_info[i].loader)(file, chunk_size, level);
3528
3529         // the size of some chunks cannot be checked before reading other
3530         // chunks first (like "HEAD" and "BODY") that contain some header
3531         // information, so check them here
3532         if (chunk_size_expected != chunk_size)
3533         {
3534           Warn("wrong size (%d) of chunk '%s' in level file '%s'",
3535                chunk_size, chunk_name, filename);
3536         }
3537       }
3538     }
3539   }
3540
3541   closeFile(file);
3542 }
3543
3544
3545 // ----------------------------------------------------------------------------
3546 // functions for loading EM level
3547 // ----------------------------------------------------------------------------
3548
3549 static void CopyNativeLevel_RND_to_EM(struct LevelInfo *level)
3550 {
3551   static int ball_xy[8][2] =
3552   {
3553     { 0, 0 },
3554     { 1, 0 },
3555     { 2, 0 },
3556     { 0, 1 },
3557     { 2, 1 },
3558     { 0, 2 },
3559     { 1, 2 },
3560     { 2, 2 },
3561   };
3562   struct LevelInfo_EM *level_em = level->native_em_level;
3563   struct CAVE *cav = level_em->cav;
3564   int i, j, x, y;
3565
3566   cav->width  = MIN(level->fieldx, MAX_PLAYFIELD_WIDTH);
3567   cav->height = MIN(level->fieldy, MAX_PLAYFIELD_HEIGHT);
3568
3569   cav->time_seconds     = level->time;
3570   cav->gems_needed      = level->gems_needed;
3571
3572   cav->emerald_score    = level->score[SC_EMERALD];
3573   cav->diamond_score    = level->score[SC_DIAMOND];
3574   cav->alien_score      = level->score[SC_ROBOT];
3575   cav->tank_score       = level->score[SC_SPACESHIP];
3576   cav->bug_score        = level->score[SC_BUG];
3577   cav->eater_score      = level->score[SC_YAMYAM];
3578   cav->nut_score        = level->score[SC_NUT];
3579   cav->dynamite_score   = level->score[SC_DYNAMITE];
3580   cav->key_score        = level->score[SC_KEY];
3581   cav->exit_score       = level->score[SC_TIME_BONUS];
3582
3583   cav->num_eater_arrays = level->num_yamyam_contents;
3584
3585   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
3586     for (y = 0; y < 3; y++)
3587       for (x = 0; x < 3; x++)
3588         cav->eater_array[i][y * 3 + x] =
3589           map_element_RND_to_EM_cave(level->yamyam_content[i].e[x][y]);
3590
3591   cav->amoeba_time              = level->amoeba_speed;
3592   cav->wonderwall_time          = level->time_magic_wall;
3593   cav->wheel_time               = level->time_wheel;
3594
3595   cav->android_move_time        = level->android_move_time;
3596   cav->android_clone_time       = level->android_clone_time;
3597   cav->ball_random              = level->ball_random;
3598   cav->ball_active              = level->ball_active_initial;
3599   cav->ball_time                = level->ball_time;
3600   cav->num_ball_arrays          = level->num_ball_contents;
3601
3602   cav->lenses_score             = level->lenses_score;
3603   cav->magnify_score            = level->magnify_score;
3604   cav->slurp_score              = level->slurp_score;
3605
3606   cav->lenses_time              = level->lenses_time;
3607   cav->magnify_time             = level->magnify_time;
3608
3609   cav->wind_direction =
3610     map_direction_RND_to_EM(level->wind_direction_initial);
3611
3612   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
3613     for (j = 0; j < 8; j++)
3614       cav->ball_array[i][j] =
3615         map_element_RND_to_EM_cave(level->ball_content[i].
3616                                    e[ball_xy[j][0]][ball_xy[j][1]]);
3617
3618   map_android_clone_elements_RND_to_EM(level);
3619
3620   // first fill the complete playfield with the empty space element
3621   for (y = 0; y < EM_MAX_CAVE_HEIGHT; y++)
3622     for (x = 0; x < EM_MAX_CAVE_WIDTH; x++)
3623       cav->cave[x][y] = Cblank;
3624
3625   // then copy the real level contents from level file into the playfield
3626   for (y = 0; y < cav->height; y++) for (x = 0; x < cav->width; x++)
3627   {
3628     int new_element = map_element_RND_to_EM_cave(level->field[x][y]);
3629
3630     if (level->field[x][y] == EL_AMOEBA_DEAD)
3631       new_element = map_element_RND_to_EM_cave(EL_AMOEBA_WET);
3632
3633     cav->cave[x][y] = new_element;
3634   }
3635
3636   for (i = 0; i < MAX_PLAYERS; i++)
3637   {
3638     cav->player_x[i] = -1;
3639     cav->player_y[i] = -1;
3640   }
3641
3642   // initialize player positions and delete players from the playfield
3643   for (y = 0; y < cav->height; y++) for (x = 0; x < cav->width; x++)
3644   {
3645     if (IS_PLAYER_ELEMENT(level->field[x][y]))
3646     {
3647       int player_nr = GET_PLAYER_NR(level->field[x][y]);
3648
3649       cav->player_x[player_nr] = x;
3650       cav->player_y[player_nr] = y;
3651
3652       cav->cave[x][y] = map_element_RND_to_EM_cave(EL_EMPTY);
3653     }
3654   }
3655 }
3656
3657 static void CopyNativeLevel_EM_to_RND(struct LevelInfo *level)
3658 {
3659   static int ball_xy[8][2] =
3660   {
3661     { 0, 0 },
3662     { 1, 0 },
3663     { 2, 0 },
3664     { 0, 1 },
3665     { 2, 1 },
3666     { 0, 2 },
3667     { 1, 2 },
3668     { 2, 2 },
3669   };
3670   struct LevelInfo_EM *level_em = level->native_em_level;
3671   struct CAVE *cav = level_em->cav;
3672   int i, j, x, y;
3673
3674   level->fieldx = MIN(cav->width,  MAX_LEV_FIELDX);
3675   level->fieldy = MIN(cav->height, MAX_LEV_FIELDY);
3676
3677   level->time        = cav->time_seconds;
3678   level->gems_needed = cav->gems_needed;
3679
3680   sprintf(level->name, "Level %d", level->file_info.nr);
3681
3682   level->score[SC_EMERALD]      = cav->emerald_score;
3683   level->score[SC_DIAMOND]      = cav->diamond_score;
3684   level->score[SC_ROBOT]        = cav->alien_score;
3685   level->score[SC_SPACESHIP]    = cav->tank_score;
3686   level->score[SC_BUG]          = cav->bug_score;
3687   level->score[SC_YAMYAM]       = cav->eater_score;
3688   level->score[SC_NUT]          = cav->nut_score;
3689   level->score[SC_DYNAMITE]     = cav->dynamite_score;
3690   level->score[SC_KEY]          = cav->key_score;
3691   level->score[SC_TIME_BONUS]   = cav->exit_score;
3692
3693   level->num_yamyam_contents    = cav->num_eater_arrays;
3694
3695   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
3696     for (y = 0; y < 3; y++)
3697       for (x = 0; x < 3; x++)
3698         level->yamyam_content[i].e[x][y] =
3699           map_element_EM_to_RND_cave(cav->eater_array[i][y * 3 + x]);
3700
3701   level->amoeba_speed           = cav->amoeba_time;
3702   level->time_magic_wall        = cav->wonderwall_time;
3703   level->time_wheel             = cav->wheel_time;
3704
3705   level->android_move_time      = cav->android_move_time;
3706   level->android_clone_time     = cav->android_clone_time;
3707   level->ball_random            = cav->ball_random;
3708   level->ball_active_initial    = cav->ball_active;
3709   level->ball_time              = cav->ball_time;
3710   level->num_ball_contents      = cav->num_ball_arrays;
3711
3712   level->lenses_score           = cav->lenses_score;
3713   level->magnify_score          = cav->magnify_score;
3714   level->slurp_score            = cav->slurp_score;
3715
3716   level->lenses_time            = cav->lenses_time;
3717   level->magnify_time           = cav->magnify_time;
3718
3719   level->wind_direction_initial =
3720     map_direction_EM_to_RND(cav->wind_direction);
3721
3722   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
3723     for (j = 0; j < 8; j++)
3724       level->ball_content[i].e[ball_xy[j][0]][ball_xy[j][1]] =
3725         map_element_EM_to_RND_cave(cav->ball_array[i][j]);
3726
3727   map_android_clone_elements_EM_to_RND(level);
3728
3729   // convert the playfield (some elements need special treatment)
3730   for (y = 0; y < level->fieldy; y++) for (x = 0; x < level->fieldx; x++)
3731   {
3732     int new_element = map_element_EM_to_RND_cave(cav->cave[x][y]);
3733
3734     if (new_element == EL_AMOEBA_WET && level->amoeba_speed == 0)
3735       new_element = EL_AMOEBA_DEAD;
3736
3737     level->field[x][y] = new_element;
3738   }
3739
3740   for (i = 0; i < MAX_PLAYERS; i++)
3741   {
3742     // in case of all players set to the same field, use the first player
3743     int nr = MAX_PLAYERS - i - 1;
3744     int jx = cav->player_x[nr];
3745     int jy = cav->player_y[nr];
3746
3747     if (jx != -1 && jy != -1)
3748       level->field[jx][jy] = EL_PLAYER_1 + nr;
3749   }
3750
3751   // time score is counted for each 10 seconds left in Emerald Mine levels
3752   level->time_score_base = 10;
3753 }
3754
3755
3756 // ----------------------------------------------------------------------------
3757 // functions for loading SP level
3758 // ----------------------------------------------------------------------------
3759
3760 static void CopyNativeLevel_RND_to_SP(struct LevelInfo *level)
3761 {
3762   struct LevelInfo_SP *level_sp = level->native_sp_level;
3763   LevelInfoType *header = &level_sp->header;
3764   int i, x, y;
3765
3766   level_sp->width  = level->fieldx;
3767   level_sp->height = level->fieldy;
3768
3769   for (x = 0; x < level->fieldx; x++)
3770     for (y = 0; y < level->fieldy; y++)
3771       level_sp->playfield[x][y] = map_element_RND_to_SP(level->field[x][y]);
3772
3773   header->InitialGravity = (level->initial_player_gravity[0] ? 1 : 0);
3774
3775   for (i = 0; i < SP_LEVEL_NAME_LEN; i++)
3776     header->LevelTitle[i] = level->name[i];
3777   // !!! NO STRING TERMINATION IN SUPAPLEX VB CODE YET -- FIX THIS !!!
3778
3779   header->InfotronsNeeded = level->gems_needed;
3780
3781   header->SpecialPortCount = 0;
3782
3783   for (x = 0; x < level->fieldx; x++) for (y = 0; y < level->fieldy; y++)
3784   {
3785     boolean gravity_port_found = FALSE;
3786     boolean gravity_port_valid = FALSE;
3787     int gravity_port_flag;
3788     int gravity_port_base_element;
3789     int element = level->field[x][y];
3790
3791     if (element >= EL_SP_GRAVITY_ON_PORT_RIGHT &&
3792         element <= EL_SP_GRAVITY_ON_PORT_UP)
3793     {
3794       gravity_port_found = TRUE;
3795       gravity_port_valid = TRUE;
3796       gravity_port_flag = 1;
3797       gravity_port_base_element = EL_SP_GRAVITY_ON_PORT_RIGHT;
3798     }
3799     else if (element >= EL_SP_GRAVITY_OFF_PORT_RIGHT &&
3800              element <= EL_SP_GRAVITY_OFF_PORT_UP)
3801     {
3802       gravity_port_found = TRUE;
3803       gravity_port_valid = TRUE;
3804       gravity_port_flag = 0;
3805       gravity_port_base_element = EL_SP_GRAVITY_OFF_PORT_RIGHT;
3806     }
3807     else if (element >= EL_SP_GRAVITY_PORT_RIGHT &&
3808              element <= EL_SP_GRAVITY_PORT_UP)
3809     {
3810       // change R'n'D style gravity inverting special port to normal port
3811       // (there are no gravity inverting ports in native Supaplex engine)
3812
3813       gravity_port_found = TRUE;
3814       gravity_port_valid = FALSE;
3815       gravity_port_base_element = EL_SP_GRAVITY_PORT_RIGHT;
3816     }
3817
3818     if (gravity_port_found)
3819     {
3820       if (gravity_port_valid &&
3821           header->SpecialPortCount < SP_MAX_SPECIAL_PORTS)
3822       {
3823         SpecialPortType *port = &header->SpecialPort[header->SpecialPortCount];
3824
3825         port->PortLocation = (y * level->fieldx + x) * 2;
3826         port->Gravity = gravity_port_flag;
3827
3828         element += EL_SP_GRAVITY_PORT_RIGHT - gravity_port_base_element;
3829
3830         header->SpecialPortCount++;
3831       }
3832       else
3833       {
3834         // change special gravity port to normal port
3835
3836         element += EL_SP_PORT_RIGHT - gravity_port_base_element;
3837       }
3838
3839       level_sp->playfield[x][y] = element - EL_SP_START;
3840     }
3841   }
3842 }
3843
3844 static void CopyNativeLevel_SP_to_RND(struct LevelInfo *level)
3845 {
3846   struct LevelInfo_SP *level_sp = level->native_sp_level;
3847   LevelInfoType *header = &level_sp->header;
3848   boolean num_invalid_elements = 0;
3849   int i, j, x, y;
3850
3851   level->fieldx = level_sp->width;
3852   level->fieldy = level_sp->height;
3853
3854   for (x = 0; x < level->fieldx; x++)
3855   {
3856     for (y = 0; y < level->fieldy; y++)
3857     {
3858       int element_old = level_sp->playfield[x][y];
3859       int element_new = getMappedElement(map_element_SP_to_RND(element_old));
3860
3861       if (element_new == EL_UNKNOWN)
3862       {
3863         num_invalid_elements++;
3864
3865         Debug("level:native:SP", "invalid element %d at position %d, %d",
3866               element_old, x, y);
3867       }
3868
3869       level->field[x][y] = element_new;
3870     }
3871   }
3872
3873   if (num_invalid_elements > 0)
3874     Warn("found %d invalid elements%s", num_invalid_elements,
3875          (!options.debug ? " (use '--debug' for more details)" : ""));
3876
3877   for (i = 0; i < MAX_PLAYERS; i++)
3878     level->initial_player_gravity[i] =
3879       (header->InitialGravity == 1 ? TRUE : FALSE);
3880
3881   // skip leading spaces
3882   for (i = 0; i < SP_LEVEL_NAME_LEN; i++)
3883     if (header->LevelTitle[i] != ' ')
3884       break;
3885
3886   // copy level title
3887   for (j = 0; i < SP_LEVEL_NAME_LEN; i++, j++)
3888     level->name[j] = header->LevelTitle[i];
3889   level->name[j] = '\0';
3890
3891   // cut trailing spaces
3892   for (; j > 0; j--)
3893     if (level->name[j - 1] == ' ' && level->name[j] == '\0')
3894       level->name[j - 1] = '\0';
3895
3896   level->gems_needed = header->InfotronsNeeded;
3897
3898   for (i = 0; i < header->SpecialPortCount; i++)
3899   {
3900     SpecialPortType *port = &header->SpecialPort[i];
3901     int port_location = port->PortLocation;
3902     int gravity = port->Gravity;
3903     int port_x, port_y, port_element;
3904
3905     port_x = (port_location / 2) % level->fieldx;
3906     port_y = (port_location / 2) / level->fieldx;
3907
3908     if (port_x < 0 || port_x >= level->fieldx ||
3909         port_y < 0 || port_y >= level->fieldy)
3910     {
3911       Warn("special port position (%d, %d) out of bounds", port_x, port_y);
3912
3913       continue;
3914     }
3915
3916     port_element = level->field[port_x][port_y];
3917
3918     if (port_element < EL_SP_GRAVITY_PORT_RIGHT ||
3919         port_element > EL_SP_GRAVITY_PORT_UP)
3920     {
3921       Warn("no special port at position (%d, %d)", port_x, port_y);
3922
3923       continue;
3924     }
3925
3926     // change previous (wrong) gravity inverting special port to either
3927     // gravity enabling special port or gravity disabling special port
3928     level->field[port_x][port_y] +=
3929       (gravity == 1 ? EL_SP_GRAVITY_ON_PORT_RIGHT :
3930        EL_SP_GRAVITY_OFF_PORT_RIGHT) - EL_SP_GRAVITY_PORT_RIGHT;
3931   }
3932
3933   // change special gravity ports without database entries to normal ports
3934   for (x = 0; x < level->fieldx; x++)
3935     for (y = 0; y < level->fieldy; y++)
3936       if (level->field[x][y] >= EL_SP_GRAVITY_PORT_RIGHT &&
3937           level->field[x][y] <= EL_SP_GRAVITY_PORT_UP)
3938         level->field[x][y] += EL_SP_PORT_RIGHT - EL_SP_GRAVITY_PORT_RIGHT;
3939
3940   level->time = 0;                      // no time limit
3941   level->amoeba_speed = 0;
3942   level->time_magic_wall = 0;
3943   level->time_wheel = 0;
3944   level->amoeba_content = EL_EMPTY;
3945
3946   // original Supaplex does not use score values -- rate by playing time
3947   for (i = 0; i < LEVEL_SCORE_ELEMENTS; i++)
3948     level->score[i] = 0;
3949
3950   level->rate_time_over_score = TRUE;
3951
3952   // there are no yamyams in supaplex levels
3953   for (i = 0; i < level->num_yamyam_contents; i++)
3954     for (x = 0; x < 3; x++)
3955       for (y = 0; y < 3; y++)
3956         level->yamyam_content[i].e[x][y] = EL_EMPTY;
3957 }
3958
3959 static void CopyNativeTape_RND_to_SP(struct LevelInfo *level)
3960 {
3961   struct LevelInfo_SP *level_sp = level->native_sp_level;
3962   struct DemoInfo_SP *demo = &level_sp->demo;
3963   int i, j;
3964
3965   // always start with reliable default values
3966   demo->is_available = FALSE;
3967   demo->length = 0;
3968
3969   if (TAPE_IS_EMPTY(tape))
3970     return;
3971
3972   demo->level_nr = tape.level_nr;       // (currently not used)
3973
3974   level_sp->header.DemoRandomSeed = tape.random_seed;
3975
3976   demo->length = 0;
3977
3978   for (i = 0; i < tape.length; i++)
3979   {
3980     int demo_action = map_key_RND_to_SP(tape.pos[i].action[0]);
3981     int demo_repeat = tape.pos[i].delay;
3982     int demo_entries = (demo_repeat + 15) / 16;
3983
3984     if (demo->length + demo_entries >= SP_MAX_TAPE_LEN)
3985     {
3986       Warn("tape truncated: size exceeds maximum SP demo size %d",
3987            SP_MAX_TAPE_LEN);
3988
3989       break;
3990     }
3991
3992     for (j = 0; j < demo_repeat / 16; j++)
3993       demo->data[demo->length++] = 0xf0 | demo_action;
3994
3995     if (demo_repeat % 16)
3996       demo->data[demo->length++] = ((demo_repeat % 16 - 1) << 4) | demo_action;
3997   }
3998
3999   demo->is_available = TRUE;
4000 }
4001
4002 static void setTapeInfoToDefaults(void);
4003
4004 static void CopyNativeTape_SP_to_RND(struct LevelInfo *level)
4005 {
4006   struct LevelInfo_SP *level_sp = level->native_sp_level;
4007   struct DemoInfo_SP *demo = &level_sp->demo;
4008   char *filename = level->file_info.filename;
4009   int i;
4010
4011   // always start with reliable default values
4012   setTapeInfoToDefaults();
4013
4014   if (!demo->is_available)
4015     return;
4016
4017   tape.level_nr = demo->level_nr;       // (currently not used)
4018   tape.random_seed = level_sp->header.DemoRandomSeed;
4019
4020   TapeSetDateFromEpochSeconds(getFileTimestampEpochSeconds(filename));
4021
4022   tape.counter = 0;
4023   tape.pos[tape.counter].delay = 0;
4024
4025   for (i = 0; i < demo->length; i++)
4026   {
4027     int demo_action = demo->data[i] & 0x0f;
4028     int demo_repeat = (demo->data[i] & 0xf0) >> 4;
4029     int tape_action = map_key_SP_to_RND(demo_action);
4030     int tape_repeat = demo_repeat + 1;
4031     byte action[MAX_TAPE_ACTIONS] = { tape_action };
4032     boolean success = 0;
4033     int j;
4034
4035     for (j = 0; j < tape_repeat; j++)
4036       success = TapeAddAction(action);
4037
4038     if (!success)
4039     {
4040       Warn("SP demo truncated: size exceeds maximum tape size %d",
4041            MAX_TAPE_LEN);
4042
4043       break;
4044     }
4045   }
4046
4047   TapeHaltRecording();
4048 }
4049
4050
4051 // ----------------------------------------------------------------------------
4052 // functions for loading MM level
4053 // ----------------------------------------------------------------------------
4054
4055 static void CopyNativeLevel_RND_to_MM(struct LevelInfo *level)
4056 {
4057   struct LevelInfo_MM *level_mm = level->native_mm_level;
4058   int x, y;
4059
4060   level_mm->fieldx = MIN(level->fieldx, MM_MAX_PLAYFIELD_WIDTH);
4061   level_mm->fieldy = MIN(level->fieldy, MM_MAX_PLAYFIELD_HEIGHT);
4062
4063   level_mm->time = level->time;
4064   level_mm->kettles_needed = level->gems_needed;
4065   level_mm->auto_count_kettles = level->auto_count_gems;
4066
4067   level_mm->laser_red = level->mm_laser_red;
4068   level_mm->laser_green = level->mm_laser_green;
4069   level_mm->laser_blue = level->mm_laser_blue;
4070
4071   strcpy(level_mm->name, level->name);
4072   strcpy(level_mm->author, level->author);
4073
4074   level_mm->score[SC_EMERALD]    = level->score[SC_EMERALD];
4075   level_mm->score[SC_PACMAN]     = level->score[SC_PACMAN];
4076   level_mm->score[SC_KEY]        = level->score[SC_KEY];
4077   level_mm->score[SC_TIME_BONUS] = level->score[SC_TIME_BONUS];
4078   level_mm->score[SC_ELEM_BONUS] = level->score[SC_ELEM_BONUS];
4079
4080   level_mm->amoeba_speed = level->amoeba_speed;
4081   level_mm->time_fuse    = level->mm_time_fuse;
4082   level_mm->time_bomb    = level->mm_time_bomb;
4083   level_mm->time_ball    = level->mm_time_ball;
4084   level_mm->time_block   = level->mm_time_block;
4085
4086   for (x = 0; x < level->fieldx; x++)
4087     for (y = 0; y < level->fieldy; y++)
4088       Ur[x][y] =
4089         level_mm->field[x][y] = map_element_RND_to_MM(level->field[x][y]);
4090 }
4091
4092 static void CopyNativeLevel_MM_to_RND(struct LevelInfo *level)
4093 {
4094   struct LevelInfo_MM *level_mm = level->native_mm_level;
4095   int x, y;
4096
4097   level->fieldx = MIN(level_mm->fieldx, MAX_LEV_FIELDX);
4098   level->fieldy = MIN(level_mm->fieldy, MAX_LEV_FIELDY);
4099
4100   level->time = level_mm->time;
4101   level->gems_needed = level_mm->kettles_needed;
4102   level->auto_count_gems = level_mm->auto_count_kettles;
4103
4104   level->mm_laser_red = level_mm->laser_red;
4105   level->mm_laser_green = level_mm->laser_green;
4106   level->mm_laser_blue = level_mm->laser_blue;
4107
4108   strcpy(level->name, level_mm->name);
4109
4110   // only overwrite author from 'levelinfo.conf' if author defined in level
4111   if (!strEqual(level_mm->author, ANONYMOUS_NAME))
4112     strcpy(level->author, level_mm->author);
4113
4114   level->score[SC_EMERALD]    = level_mm->score[SC_EMERALD];
4115   level->score[SC_PACMAN]     = level_mm->score[SC_PACMAN];
4116   level->score[SC_KEY]        = level_mm->score[SC_KEY];
4117   level->score[SC_TIME_BONUS] = level_mm->score[SC_TIME_BONUS];
4118   level->score[SC_ELEM_BONUS] = level_mm->score[SC_ELEM_BONUS];
4119
4120   level->amoeba_speed  = level_mm->amoeba_speed;
4121   level->mm_time_fuse  = level_mm->time_fuse;
4122   level->mm_time_bomb  = level_mm->time_bomb;
4123   level->mm_time_ball  = level_mm->time_ball;
4124   level->mm_time_block = level_mm->time_block;
4125
4126   for (x = 0; x < level->fieldx; x++)
4127     for (y = 0; y < level->fieldy; y++)
4128       level->field[x][y] = map_element_MM_to_RND(level_mm->field[x][y]);
4129 }
4130
4131
4132 // ----------------------------------------------------------------------------
4133 // functions for loading DC level
4134 // ----------------------------------------------------------------------------
4135
4136 #define DC_LEVEL_HEADER_SIZE            344
4137
4138 static unsigned short getDecodedWord_DC(unsigned short data_encoded,
4139                                         boolean init)
4140 {
4141   static int last_data_encoded;
4142   static int offset1;
4143   static int offset2;
4144   int diff;
4145   int diff_hi, diff_lo;
4146   int data_hi, data_lo;
4147   unsigned short data_decoded;
4148
4149   if (init)
4150   {
4151     last_data_encoded = 0;
4152     offset1 = -1;
4153     offset2 = 0;
4154
4155     return 0;
4156   }
4157
4158   diff = data_encoded - last_data_encoded;
4159   diff_hi = diff & ~0xff;
4160   diff_lo = diff &  0xff;
4161
4162   offset2 += diff_lo;
4163
4164   data_hi = diff_hi - (offset1 << 8) + (offset2 & 0xff00);
4165   data_lo = (diff_lo + (data_hi >> 16)) & 0x00ff;
4166   data_hi = data_hi & 0xff00;
4167
4168   data_decoded = data_hi | data_lo;
4169
4170   last_data_encoded = data_encoded;
4171
4172   offset1 = (offset1 + 1) % 31;
4173   offset2 = offset2 & 0xff;
4174
4175   return data_decoded;
4176 }
4177
4178 static int getMappedElement_DC(int element)
4179 {
4180   switch (element)
4181   {
4182     case 0x0000:
4183       element = EL_ROCK;
4184       break;
4185
4186       // 0x0117 - 0x036e: (?)
4187       // EL_DIAMOND
4188
4189       // 0x042d - 0x0684: (?)
4190       // EL_EMERALD
4191
4192     case 0x06f1:
4193       element = EL_NUT;
4194       break;
4195
4196     case 0x074c:
4197       element = EL_BOMB;
4198       break;
4199
4200     case 0x07a4:
4201       element = EL_PEARL;
4202       break;
4203
4204     case 0x0823:
4205       element = EL_CRYSTAL;
4206       break;
4207
4208     case 0x0e77:        // quicksand (boulder)
4209       element = EL_QUICKSAND_FAST_FULL;
4210       break;
4211
4212     case 0x0e99:        // slow quicksand (boulder)
4213       element = EL_QUICKSAND_FULL;
4214       break;
4215
4216     case 0x0ed2:
4217       element = EL_EM_EXIT_OPEN;
4218       break;
4219
4220     case 0x0ee3:
4221       element = EL_EM_EXIT_CLOSED;
4222       break;
4223
4224     case 0x0eeb:
4225       element = EL_EM_STEEL_EXIT_OPEN;
4226       break;
4227
4228     case 0x0efc:
4229       element = EL_EM_STEEL_EXIT_CLOSED;
4230       break;
4231
4232     case 0x0f4f:        // dynamite (lit 1)
4233       element = EL_EM_DYNAMITE_ACTIVE;
4234       break;
4235
4236     case 0x0f57:        // dynamite (lit 2)
4237       element = EL_EM_DYNAMITE_ACTIVE;
4238       break;
4239
4240     case 0x0f5f:        // dynamite (lit 3)
4241       element = EL_EM_DYNAMITE_ACTIVE;
4242       break;
4243
4244     case 0x0f67:        // dynamite (lit 4)
4245       element = EL_EM_DYNAMITE_ACTIVE;
4246       break;
4247
4248     case 0x0f81:
4249     case 0x0f82:
4250     case 0x0f83:
4251     case 0x0f84:
4252       element = EL_AMOEBA_WET;
4253       break;
4254
4255     case 0x0f85:
4256       element = EL_AMOEBA_DROP;
4257       break;
4258
4259     case 0x0fb9:
4260       element = EL_DC_MAGIC_WALL;
4261       break;
4262
4263     case 0x0fd0:
4264       element = EL_SPACESHIP_UP;
4265       break;
4266
4267     case 0x0fd9:
4268       element = EL_SPACESHIP_DOWN;
4269       break;
4270
4271     case 0x0ff1:
4272       element = EL_SPACESHIP_LEFT;
4273       break;
4274
4275     case 0x0ff9:
4276       element = EL_SPACESHIP_RIGHT;
4277       break;
4278
4279     case 0x1057:
4280       element = EL_BUG_UP;
4281       break;
4282
4283     case 0x1060:
4284       element = EL_BUG_DOWN;
4285       break;
4286
4287     case 0x1078:
4288       element = EL_BUG_LEFT;
4289       break;
4290
4291     case 0x1080:
4292       element = EL_BUG_RIGHT;
4293       break;
4294
4295     case 0x10de:
4296       element = EL_MOLE_UP;
4297       break;
4298
4299     case 0x10e7:
4300       element = EL_MOLE_DOWN;
4301       break;
4302
4303     case 0x10ff:
4304       element = EL_MOLE_LEFT;
4305       break;
4306
4307     case 0x1107:
4308       element = EL_MOLE_RIGHT;
4309       break;
4310
4311     case 0x11c0:
4312       element = EL_ROBOT;
4313       break;
4314
4315     case 0x13f5:
4316       element = EL_YAMYAM_UP;
4317       break;
4318
4319     case 0x1425:
4320       element = EL_SWITCHGATE_OPEN;
4321       break;
4322
4323     case 0x1426:
4324       element = EL_SWITCHGATE_CLOSED;
4325       break;
4326
4327     case 0x1437:
4328       element = EL_DC_SWITCHGATE_SWITCH_UP;
4329       break;
4330
4331     case 0x143a:
4332       element = EL_TIMEGATE_CLOSED;
4333       break;
4334
4335     case 0x144c:        // conveyor belt switch (green)
4336       element = EL_CONVEYOR_BELT_3_SWITCH_MIDDLE;
4337       break;
4338
4339     case 0x144f:        // conveyor belt switch (red)
4340       element = EL_CONVEYOR_BELT_1_SWITCH_MIDDLE;
4341       break;
4342
4343     case 0x1452:        // conveyor belt switch (blue)
4344       element = EL_CONVEYOR_BELT_4_SWITCH_MIDDLE;
4345       break;
4346
4347     case 0x145b:
4348       element = EL_CONVEYOR_BELT_3_MIDDLE;
4349       break;
4350
4351     case 0x1463:
4352       element = EL_CONVEYOR_BELT_3_LEFT;
4353       break;
4354
4355     case 0x146b:
4356       element = EL_CONVEYOR_BELT_3_RIGHT;
4357       break;
4358
4359     case 0x1473:
4360       element = EL_CONVEYOR_BELT_1_MIDDLE;
4361       break;
4362
4363     case 0x147b:
4364       element = EL_CONVEYOR_BELT_1_LEFT;
4365       break;
4366
4367     case 0x1483:
4368       element = EL_CONVEYOR_BELT_1_RIGHT;
4369       break;
4370
4371     case 0x148b:
4372       element = EL_CONVEYOR_BELT_4_MIDDLE;
4373       break;
4374
4375     case 0x1493:
4376       element = EL_CONVEYOR_BELT_4_LEFT;
4377       break;
4378
4379     case 0x149b:
4380       element = EL_CONVEYOR_BELT_4_RIGHT;
4381       break;
4382
4383     case 0x14ac:
4384       element = EL_EXPANDABLE_WALL_HORIZONTAL;
4385       break;
4386
4387     case 0x14bd:
4388       element = EL_EXPANDABLE_WALL_VERTICAL;
4389       break;
4390
4391     case 0x14c6:
4392       element = EL_EXPANDABLE_WALL_ANY;
4393       break;
4394
4395     case 0x14ce:        // growing steel wall (left/right)
4396       element = EL_EXPANDABLE_STEELWALL_HORIZONTAL;
4397       break;
4398
4399     case 0x14df:        // growing steel wall (up/down)
4400       element = EL_EXPANDABLE_STEELWALL_VERTICAL;
4401       break;
4402
4403     case 0x14e8:        // growing steel wall (up/down/left/right)
4404       element = EL_EXPANDABLE_STEELWALL_ANY;
4405       break;
4406
4407     case 0x14e9:
4408       element = EL_SHIELD_DEADLY;
4409       break;
4410
4411     case 0x1501:
4412       element = EL_EXTRA_TIME;
4413       break;
4414
4415     case 0x154f:
4416       element = EL_ACID;
4417       break;
4418
4419     case 0x1577:
4420       element = EL_EMPTY_SPACE;
4421       break;
4422
4423     case 0x1578:        // quicksand (empty)
4424       element = EL_QUICKSAND_FAST_EMPTY;
4425       break;
4426
4427     case 0x1579:        // slow quicksand (empty)
4428       element = EL_QUICKSAND_EMPTY;
4429       break;
4430
4431       // 0x157c - 0x158b:
4432       // EL_SAND
4433
4434       // 0x1590 - 0x159f:
4435       // EL_DC_LANDMINE
4436
4437     case 0x15a0:
4438       element = EL_EM_DYNAMITE;
4439       break;
4440
4441     case 0x15a1:        // key (red)
4442       element = EL_EM_KEY_1;
4443       break;
4444
4445     case 0x15a2:        // key (yellow)
4446       element = EL_EM_KEY_2;
4447       break;
4448
4449     case 0x15a3:        // key (blue)
4450       element = EL_EM_KEY_4;
4451       break;
4452
4453     case 0x15a4:        // key (green)
4454       element = EL_EM_KEY_3;
4455       break;
4456
4457     case 0x15a5:        // key (white)
4458       element = EL_DC_KEY_WHITE;
4459       break;
4460
4461     case 0x15a6:
4462       element = EL_WALL_SLIPPERY;
4463       break;
4464
4465     case 0x15a7:
4466       element = EL_WALL;
4467       break;
4468
4469     case 0x15a8:        // wall (not round)
4470       element = EL_WALL;
4471       break;
4472
4473     case 0x15a9:        // (blue)
4474       element = EL_CHAR_A;
4475       break;
4476
4477     case 0x15aa:        // (blue)
4478       element = EL_CHAR_B;
4479       break;
4480
4481     case 0x15ab:        // (blue)
4482       element = EL_CHAR_C;
4483       break;
4484
4485     case 0x15ac:        // (blue)
4486       element = EL_CHAR_D;
4487       break;
4488
4489     case 0x15ad:        // (blue)
4490       element = EL_CHAR_E;
4491       break;
4492
4493     case 0x15ae:        // (blue)
4494       element = EL_CHAR_F;
4495       break;
4496
4497     case 0x15af:        // (blue)
4498       element = EL_CHAR_G;
4499       break;
4500
4501     case 0x15b0:        // (blue)
4502       element = EL_CHAR_H;
4503       break;
4504
4505     case 0x15b1:        // (blue)
4506       element = EL_CHAR_I;
4507       break;
4508
4509     case 0x15b2:        // (blue)
4510       element = EL_CHAR_J;
4511       break;
4512
4513     case 0x15b3:        // (blue)
4514       element = EL_CHAR_K;
4515       break;
4516
4517     case 0x15b4:        // (blue)
4518       element = EL_CHAR_L;
4519       break;
4520
4521     case 0x15b5:        // (blue)
4522       element = EL_CHAR_M;
4523       break;
4524
4525     case 0x15b6:        // (blue)
4526       element = EL_CHAR_N;
4527       break;
4528
4529     case 0x15b7:        // (blue)
4530       element = EL_CHAR_O;
4531       break;
4532
4533     case 0x15b8:        // (blue)
4534       element = EL_CHAR_P;
4535       break;
4536
4537     case 0x15b9:        // (blue)
4538       element = EL_CHAR_Q;
4539       break;
4540
4541     case 0x15ba:        // (blue)
4542       element = EL_CHAR_R;
4543       break;
4544
4545     case 0x15bb:        // (blue)
4546       element = EL_CHAR_S;
4547       break;
4548
4549     case 0x15bc:        // (blue)
4550       element = EL_CHAR_T;
4551       break;
4552
4553     case 0x15bd:        // (blue)
4554       element = EL_CHAR_U;
4555       break;
4556
4557     case 0x15be:        // (blue)
4558       element = EL_CHAR_V;
4559       break;
4560
4561     case 0x15bf:        // (blue)
4562       element = EL_CHAR_W;
4563       break;
4564
4565     case 0x15c0:        // (blue)
4566       element = EL_CHAR_X;
4567       break;
4568
4569     case 0x15c1:        // (blue)
4570       element = EL_CHAR_Y;
4571       break;
4572
4573     case 0x15c2:        // (blue)
4574       element = EL_CHAR_Z;
4575       break;
4576
4577     case 0x15c3:        // (blue)
4578       element = EL_CHAR_AUMLAUT;
4579       break;
4580
4581     case 0x15c4:        // (blue)
4582       element = EL_CHAR_OUMLAUT;
4583       break;
4584
4585     case 0x15c5:        // (blue)
4586       element = EL_CHAR_UUMLAUT;
4587       break;
4588
4589     case 0x15c6:        // (blue)
4590       element = EL_CHAR_0;
4591       break;
4592
4593     case 0x15c7:        // (blue)
4594       element = EL_CHAR_1;
4595       break;
4596
4597     case 0x15c8:        // (blue)
4598       element = EL_CHAR_2;
4599       break;
4600
4601     case 0x15c9:        // (blue)
4602       element = EL_CHAR_3;
4603       break;
4604
4605     case 0x15ca:        // (blue)
4606       element = EL_CHAR_4;
4607       break;
4608
4609     case 0x15cb:        // (blue)
4610       element = EL_CHAR_5;
4611       break;
4612
4613     case 0x15cc:        // (blue)
4614       element = EL_CHAR_6;
4615       break;
4616
4617     case 0x15cd:        // (blue)
4618       element = EL_CHAR_7;
4619       break;
4620
4621     case 0x15ce:        // (blue)
4622       element = EL_CHAR_8;
4623       break;
4624
4625     case 0x15cf:        // (blue)
4626       element = EL_CHAR_9;
4627       break;
4628
4629     case 0x15d0:        // (blue)
4630       element = EL_CHAR_PERIOD;
4631       break;
4632
4633     case 0x15d1:        // (blue)
4634       element = EL_CHAR_EXCLAM;
4635       break;
4636
4637     case 0x15d2:        // (blue)
4638       element = EL_CHAR_COLON;
4639       break;
4640
4641     case 0x15d3:        // (blue)
4642       element = EL_CHAR_LESS;
4643       break;
4644
4645     case 0x15d4:        // (blue)
4646       element = EL_CHAR_GREATER;
4647       break;
4648
4649     case 0x15d5:        // (blue)
4650       element = EL_CHAR_QUESTION;
4651       break;
4652
4653     case 0x15d6:        // (blue)
4654       element = EL_CHAR_COPYRIGHT;
4655       break;
4656
4657     case 0x15d7:        // (blue)
4658       element = EL_CHAR_UP;
4659       break;
4660
4661     case 0x15d8:        // (blue)
4662       element = EL_CHAR_DOWN;
4663       break;
4664
4665     case 0x15d9:        // (blue)
4666       element = EL_CHAR_BUTTON;
4667       break;
4668
4669     case 0x15da:        // (blue)
4670       element = EL_CHAR_PLUS;
4671       break;
4672
4673     case 0x15db:        // (blue)
4674       element = EL_CHAR_MINUS;
4675       break;
4676
4677     case 0x15dc:        // (blue)
4678       element = EL_CHAR_APOSTROPHE;
4679       break;
4680
4681     case 0x15dd:        // (blue)
4682       element = EL_CHAR_PARENLEFT;
4683       break;
4684
4685     case 0x15de:        // (blue)
4686       element = EL_CHAR_PARENRIGHT;
4687       break;
4688
4689     case 0x15df:        // (green)
4690       element = EL_CHAR_A;
4691       break;
4692
4693     case 0x15e0:        // (green)
4694       element = EL_CHAR_B;
4695       break;
4696
4697     case 0x15e1:        // (green)
4698       element = EL_CHAR_C;
4699       break;
4700
4701     case 0x15e2:        // (green)
4702       element = EL_CHAR_D;
4703       break;
4704
4705     case 0x15e3:        // (green)
4706       element = EL_CHAR_E;
4707       break;
4708
4709     case 0x15e4:        // (green)
4710       element = EL_CHAR_F;
4711       break;
4712
4713     case 0x15e5:        // (green)
4714       element = EL_CHAR_G;
4715       break;
4716
4717     case 0x15e6:        // (green)
4718       element = EL_CHAR_H;
4719       break;
4720
4721     case 0x15e7:        // (green)
4722       element = EL_CHAR_I;
4723       break;
4724
4725     case 0x15e8:        // (green)
4726       element = EL_CHAR_J;
4727       break;
4728
4729     case 0x15e9:        // (green)
4730       element = EL_CHAR_K;
4731       break;
4732
4733     case 0x15ea:        // (green)
4734       element = EL_CHAR_L;
4735       break;
4736
4737     case 0x15eb:        // (green)
4738       element = EL_CHAR_M;
4739       break;
4740
4741     case 0x15ec:        // (green)
4742       element = EL_CHAR_N;
4743       break;
4744
4745     case 0x15ed:        // (green)
4746       element = EL_CHAR_O;
4747       break;
4748
4749     case 0x15ee:        // (green)
4750       element = EL_CHAR_P;
4751       break;
4752
4753     case 0x15ef:        // (green)
4754       element = EL_CHAR_Q;
4755       break;
4756
4757     case 0x15f0:        // (green)
4758       element = EL_CHAR_R;
4759       break;
4760
4761     case 0x15f1:        // (green)
4762       element = EL_CHAR_S;
4763       break;
4764
4765     case 0x15f2:        // (green)
4766       element = EL_CHAR_T;
4767       break;
4768
4769     case 0x15f3:        // (green)
4770       element = EL_CHAR_U;
4771       break;
4772
4773     case 0x15f4:        // (green)
4774       element = EL_CHAR_V;
4775       break;
4776
4777     case 0x15f5:        // (green)
4778       element = EL_CHAR_W;
4779       break;
4780
4781     case 0x15f6:        // (green)
4782       element = EL_CHAR_X;
4783       break;
4784
4785     case 0x15f7:        // (green)
4786       element = EL_CHAR_Y;
4787       break;
4788
4789     case 0x15f8:        // (green)
4790       element = EL_CHAR_Z;
4791       break;
4792
4793     case 0x15f9:        // (green)
4794       element = EL_CHAR_AUMLAUT;
4795       break;
4796
4797     case 0x15fa:        // (green)
4798       element = EL_CHAR_OUMLAUT;
4799       break;
4800
4801     case 0x15fb:        // (green)
4802       element = EL_CHAR_UUMLAUT;
4803       break;
4804
4805     case 0x15fc:        // (green)
4806       element = EL_CHAR_0;
4807       break;
4808
4809     case 0x15fd:        // (green)
4810       element = EL_CHAR_1;
4811       break;
4812
4813     case 0x15fe:        // (green)
4814       element = EL_CHAR_2;
4815       break;
4816
4817     case 0x15ff:        // (green)
4818       element = EL_CHAR_3;
4819       break;
4820
4821     case 0x1600:        // (green)
4822       element = EL_CHAR_4;
4823       break;
4824
4825     case 0x1601:        // (green)
4826       element = EL_CHAR_5;
4827       break;
4828
4829     case 0x1602:        // (green)
4830       element = EL_CHAR_6;
4831       break;
4832
4833     case 0x1603:        // (green)
4834       element = EL_CHAR_7;
4835       break;
4836
4837     case 0x1604:        // (green)
4838       element = EL_CHAR_8;
4839       break;
4840
4841     case 0x1605:        // (green)
4842       element = EL_CHAR_9;
4843       break;
4844
4845     case 0x1606:        // (green)
4846       element = EL_CHAR_PERIOD;
4847       break;
4848
4849     case 0x1607:        // (green)
4850       element = EL_CHAR_EXCLAM;
4851       break;
4852
4853     case 0x1608:        // (green)
4854       element = EL_CHAR_COLON;
4855       break;
4856
4857     case 0x1609:        // (green)
4858       element = EL_CHAR_LESS;
4859       break;
4860
4861     case 0x160a:        // (green)
4862       element = EL_CHAR_GREATER;
4863       break;
4864
4865     case 0x160b:        // (green)
4866       element = EL_CHAR_QUESTION;
4867       break;
4868
4869     case 0x160c:        // (green)
4870       element = EL_CHAR_COPYRIGHT;
4871       break;
4872
4873     case 0x160d:        // (green)
4874       element = EL_CHAR_UP;
4875       break;
4876
4877     case 0x160e:        // (green)
4878       element = EL_CHAR_DOWN;
4879       break;
4880
4881     case 0x160f:        // (green)
4882       element = EL_CHAR_BUTTON;
4883       break;
4884
4885     case 0x1610:        // (green)
4886       element = EL_CHAR_PLUS;
4887       break;
4888
4889     case 0x1611:        // (green)
4890       element = EL_CHAR_MINUS;
4891       break;
4892
4893     case 0x1612:        // (green)
4894       element = EL_CHAR_APOSTROPHE;
4895       break;
4896
4897     case 0x1613:        // (green)
4898       element = EL_CHAR_PARENLEFT;
4899       break;
4900
4901     case 0x1614:        // (green)
4902       element = EL_CHAR_PARENRIGHT;
4903       break;
4904
4905     case 0x1615:        // (blue steel)
4906       element = EL_STEEL_CHAR_A;
4907       break;
4908
4909     case 0x1616:        // (blue steel)
4910       element = EL_STEEL_CHAR_B;
4911       break;
4912
4913     case 0x1617:        // (blue steel)
4914       element = EL_STEEL_CHAR_C;
4915       break;
4916
4917     case 0x1618:        // (blue steel)
4918       element = EL_STEEL_CHAR_D;
4919       break;
4920
4921     case 0x1619:        // (blue steel)
4922       element = EL_STEEL_CHAR_E;
4923       break;
4924
4925     case 0x161a:        // (blue steel)
4926       element = EL_STEEL_CHAR_F;
4927       break;
4928
4929     case 0x161b:        // (blue steel)
4930       element = EL_STEEL_CHAR_G;
4931       break;
4932
4933     case 0x161c:        // (blue steel)
4934       element = EL_STEEL_CHAR_H;
4935       break;
4936
4937     case 0x161d:        // (blue steel)
4938       element = EL_STEEL_CHAR_I;
4939       break;
4940
4941     case 0x161e:        // (blue steel)
4942       element = EL_STEEL_CHAR_J;
4943       break;
4944
4945     case 0x161f:        // (blue steel)
4946       element = EL_STEEL_CHAR_K;
4947       break;
4948
4949     case 0x1620:        // (blue steel)
4950       element = EL_STEEL_CHAR_L;
4951       break;
4952
4953     case 0x1621:        // (blue steel)
4954       element = EL_STEEL_CHAR_M;
4955       break;
4956
4957     case 0x1622:        // (blue steel)
4958       element = EL_STEEL_CHAR_N;
4959       break;
4960
4961     case 0x1623:        // (blue steel)
4962       element = EL_STEEL_CHAR_O;
4963       break;
4964
4965     case 0x1624:        // (blue steel)
4966       element = EL_STEEL_CHAR_P;
4967       break;
4968
4969     case 0x1625:        // (blue steel)
4970       element = EL_STEEL_CHAR_Q;
4971       break;
4972
4973     case 0x1626:        // (blue steel)
4974       element = EL_STEEL_CHAR_R;
4975       break;
4976
4977     case 0x1627:        // (blue steel)
4978       element = EL_STEEL_CHAR_S;
4979       break;
4980
4981     case 0x1628:        // (blue steel)
4982       element = EL_STEEL_CHAR_T;
4983       break;
4984
4985     case 0x1629:        // (blue steel)
4986       element = EL_STEEL_CHAR_U;
4987       break;
4988
4989     case 0x162a:        // (blue steel)
4990       element = EL_STEEL_CHAR_V;
4991       break;
4992
4993     case 0x162b:        // (blue steel)
4994       element = EL_STEEL_CHAR_W;
4995       break;
4996
4997     case 0x162c:        // (blue steel)
4998       element = EL_STEEL_CHAR_X;
4999       break;
5000
5001     case 0x162d:        // (blue steel)
5002       element = EL_STEEL_CHAR_Y;
5003       break;
5004
5005     case 0x162e:        // (blue steel)
5006       element = EL_STEEL_CHAR_Z;
5007       break;
5008
5009     case 0x162f:        // (blue steel)
5010       element = EL_STEEL_CHAR_AUMLAUT;
5011       break;
5012
5013     case 0x1630:        // (blue steel)
5014       element = EL_STEEL_CHAR_OUMLAUT;
5015       break;
5016
5017     case 0x1631:        // (blue steel)
5018       element = EL_STEEL_CHAR_UUMLAUT;
5019       break;
5020
5021     case 0x1632:        // (blue steel)
5022       element = EL_STEEL_CHAR_0;
5023       break;
5024
5025     case 0x1633:        // (blue steel)
5026       element = EL_STEEL_CHAR_1;
5027       break;
5028
5029     case 0x1634:        // (blue steel)
5030       element = EL_STEEL_CHAR_2;
5031       break;
5032
5033     case 0x1635:        // (blue steel)
5034       element = EL_STEEL_CHAR_3;
5035       break;
5036
5037     case 0x1636:        // (blue steel)
5038       element = EL_STEEL_CHAR_4;
5039       break;
5040
5041     case 0x1637:        // (blue steel)
5042       element = EL_STEEL_CHAR_5;
5043       break;
5044
5045     case 0x1638:        // (blue steel)
5046       element = EL_STEEL_CHAR_6;
5047       break;
5048
5049     case 0x1639:        // (blue steel)
5050       element = EL_STEEL_CHAR_7;
5051       break;
5052
5053     case 0x163a:        // (blue steel)
5054       element = EL_STEEL_CHAR_8;
5055       break;
5056
5057     case 0x163b:        // (blue steel)
5058       element = EL_STEEL_CHAR_9;
5059       break;
5060
5061     case 0x163c:        // (blue steel)
5062       element = EL_STEEL_CHAR_PERIOD;
5063       break;
5064
5065     case 0x163d:        // (blue steel)
5066       element = EL_STEEL_CHAR_EXCLAM;
5067       break;
5068
5069     case 0x163e:        // (blue steel)
5070       element = EL_STEEL_CHAR_COLON;
5071       break;
5072
5073     case 0x163f:        // (blue steel)
5074       element = EL_STEEL_CHAR_LESS;
5075       break;
5076
5077     case 0x1640:        // (blue steel)
5078       element = EL_STEEL_CHAR_GREATER;
5079       break;
5080
5081     case 0x1641:        // (blue steel)
5082       element = EL_STEEL_CHAR_QUESTION;
5083       break;
5084
5085     case 0x1642:        // (blue steel)
5086       element = EL_STEEL_CHAR_COPYRIGHT;
5087       break;
5088
5089     case 0x1643:        // (blue steel)
5090       element = EL_STEEL_CHAR_UP;
5091       break;
5092
5093     case 0x1644:        // (blue steel)
5094       element = EL_STEEL_CHAR_DOWN;
5095       break;
5096
5097     case 0x1645:        // (blue steel)
5098       element = EL_STEEL_CHAR_BUTTON;
5099       break;
5100
5101     case 0x1646:        // (blue steel)
5102       element = EL_STEEL_CHAR_PLUS;
5103       break;
5104
5105     case 0x1647:        // (blue steel)
5106       element = EL_STEEL_CHAR_MINUS;
5107       break;
5108
5109     case 0x1648:        // (blue steel)
5110       element = EL_STEEL_CHAR_APOSTROPHE;
5111       break;
5112
5113     case 0x1649:        // (blue steel)
5114       element = EL_STEEL_CHAR_PARENLEFT;
5115       break;
5116
5117     case 0x164a:        // (blue steel)
5118       element = EL_STEEL_CHAR_PARENRIGHT;
5119       break;
5120
5121     case 0x164b:        // (green steel)
5122       element = EL_STEEL_CHAR_A;
5123       break;
5124
5125     case 0x164c:        // (green steel)
5126       element = EL_STEEL_CHAR_B;
5127       break;
5128
5129     case 0x164d:        // (green steel)
5130       element = EL_STEEL_CHAR_C;
5131       break;
5132
5133     case 0x164e:        // (green steel)
5134       element = EL_STEEL_CHAR_D;
5135       break;
5136
5137     case 0x164f:        // (green steel)
5138       element = EL_STEEL_CHAR_E;
5139       break;
5140
5141     case 0x1650:        // (green steel)
5142       element = EL_STEEL_CHAR_F;
5143       break;
5144
5145     case 0x1651:        // (green steel)
5146       element = EL_STEEL_CHAR_G;
5147       break;
5148
5149     case 0x1652:        // (green steel)
5150       element = EL_STEEL_CHAR_H;
5151       break;
5152
5153     case 0x1653:        // (green steel)
5154       element = EL_STEEL_CHAR_I;
5155       break;
5156
5157     case 0x1654:        // (green steel)
5158       element = EL_STEEL_CHAR_J;
5159       break;
5160
5161     case 0x1655:        // (green steel)
5162       element = EL_STEEL_CHAR_K;
5163       break;
5164
5165     case 0x1656:        // (green steel)
5166       element = EL_STEEL_CHAR_L;
5167       break;
5168
5169     case 0x1657:        // (green steel)
5170       element = EL_STEEL_CHAR_M;
5171       break;
5172
5173     case 0x1658:        // (green steel)
5174       element = EL_STEEL_CHAR_N;
5175       break;
5176
5177     case 0x1659:        // (green steel)
5178       element = EL_STEEL_CHAR_O;
5179       break;
5180
5181     case 0x165a:        // (green steel)
5182       element = EL_STEEL_CHAR_P;
5183       break;
5184
5185     case 0x165b:        // (green steel)
5186       element = EL_STEEL_CHAR_Q;
5187       break;
5188
5189     case 0x165c:        // (green steel)
5190       element = EL_STEEL_CHAR_R;
5191       break;
5192
5193     case 0x165d:        // (green steel)
5194       element = EL_STEEL_CHAR_S;
5195       break;
5196
5197     case 0x165e:        // (green steel)
5198       element = EL_STEEL_CHAR_T;
5199       break;
5200
5201     case 0x165f:        // (green steel)
5202       element = EL_STEEL_CHAR_U;
5203       break;
5204
5205     case 0x1660:        // (green steel)
5206       element = EL_STEEL_CHAR_V;
5207       break;
5208
5209     case 0x1661:        // (green steel)
5210       element = EL_STEEL_CHAR_W;
5211       break;
5212
5213     case 0x1662:        // (green steel)
5214       element = EL_STEEL_CHAR_X;
5215       break;
5216
5217     case 0x1663:        // (green steel)
5218       element = EL_STEEL_CHAR_Y;
5219       break;
5220
5221     case 0x1664:        // (green steel)
5222       element = EL_STEEL_CHAR_Z;
5223       break;
5224
5225     case 0x1665:        // (green steel)
5226       element = EL_STEEL_CHAR_AUMLAUT;
5227       break;
5228
5229     case 0x1666:        // (green steel)
5230       element = EL_STEEL_CHAR_OUMLAUT;
5231       break;
5232
5233     case 0x1667:        // (green steel)
5234       element = EL_STEEL_CHAR_UUMLAUT;
5235       break;
5236
5237     case 0x1668:        // (green steel)
5238       element = EL_STEEL_CHAR_0;
5239       break;
5240
5241     case 0x1669:        // (green steel)
5242       element = EL_STEEL_CHAR_1;
5243       break;
5244
5245     case 0x166a:        // (green steel)
5246       element = EL_STEEL_CHAR_2;
5247       break;
5248
5249     case 0x166b:        // (green steel)
5250       element = EL_STEEL_CHAR_3;
5251       break;
5252
5253     case 0x166c:        // (green steel)
5254       element = EL_STEEL_CHAR_4;
5255       break;
5256
5257     case 0x166d:        // (green steel)
5258       element = EL_STEEL_CHAR_5;
5259       break;
5260
5261     case 0x166e:        // (green steel)
5262       element = EL_STEEL_CHAR_6;
5263       break;
5264
5265     case 0x166f:        // (green steel)
5266       element = EL_STEEL_CHAR_7;
5267       break;
5268
5269     case 0x1670:        // (green steel)
5270       element = EL_STEEL_CHAR_8;
5271       break;
5272
5273     case 0x1671:        // (green steel)
5274       element = EL_STEEL_CHAR_9;
5275       break;
5276
5277     case 0x1672:        // (green steel)
5278       element = EL_STEEL_CHAR_PERIOD;
5279       break;
5280
5281     case 0x1673:        // (green steel)
5282       element = EL_STEEL_CHAR_EXCLAM;
5283       break;
5284
5285     case 0x1674:        // (green steel)
5286       element = EL_STEEL_CHAR_COLON;
5287       break;
5288
5289     case 0x1675:        // (green steel)
5290       element = EL_STEEL_CHAR_LESS;
5291       break;
5292
5293     case 0x1676:        // (green steel)
5294       element = EL_STEEL_CHAR_GREATER;
5295       break;
5296
5297     case 0x1677:        // (green steel)
5298       element = EL_STEEL_CHAR_QUESTION;
5299       break;
5300
5301     case 0x1678:        // (green steel)
5302       element = EL_STEEL_CHAR_COPYRIGHT;
5303       break;
5304
5305     case 0x1679:        // (green steel)
5306       element = EL_STEEL_CHAR_UP;
5307       break;
5308
5309     case 0x167a:        // (green steel)
5310       element = EL_STEEL_CHAR_DOWN;
5311       break;
5312
5313     case 0x167b:        // (green steel)
5314       element = EL_STEEL_CHAR_BUTTON;
5315       break;
5316
5317     case 0x167c:        // (green steel)
5318       element = EL_STEEL_CHAR_PLUS;
5319       break;
5320
5321     case 0x167d:        // (green steel)
5322       element = EL_STEEL_CHAR_MINUS;
5323       break;
5324
5325     case 0x167e:        // (green steel)
5326       element = EL_STEEL_CHAR_APOSTROPHE;
5327       break;
5328
5329     case 0x167f:        // (green steel)
5330       element = EL_STEEL_CHAR_PARENLEFT;
5331       break;
5332
5333     case 0x1680:        // (green steel)
5334       element = EL_STEEL_CHAR_PARENRIGHT;
5335       break;
5336
5337     case 0x1681:        // gate (red)
5338       element = EL_EM_GATE_1;
5339       break;
5340
5341     case 0x1682:        // secret gate (red)
5342       element = EL_EM_GATE_1_GRAY;
5343       break;
5344
5345     case 0x1683:        // gate (yellow)
5346       element = EL_EM_GATE_2;
5347       break;
5348
5349     case 0x1684:        // secret gate (yellow)
5350       element = EL_EM_GATE_2_GRAY;
5351       break;
5352
5353     case 0x1685:        // gate (blue)
5354       element = EL_EM_GATE_4;
5355       break;
5356
5357     case 0x1686:        // secret gate (blue)
5358       element = EL_EM_GATE_4_GRAY;
5359       break;
5360
5361     case 0x1687:        // gate (green)
5362       element = EL_EM_GATE_3;
5363       break;
5364
5365     case 0x1688:        // secret gate (green)
5366       element = EL_EM_GATE_3_GRAY;
5367       break;
5368
5369     case 0x1689:        // gate (white)
5370       element = EL_DC_GATE_WHITE;
5371       break;
5372
5373     case 0x168a:        // secret gate (white)
5374       element = EL_DC_GATE_WHITE_GRAY;
5375       break;
5376
5377     case 0x168b:        // secret gate (no key)
5378       element = EL_DC_GATE_FAKE_GRAY;
5379       break;
5380
5381     case 0x168c:
5382       element = EL_ROBOT_WHEEL;
5383       break;
5384
5385     case 0x168d:
5386       element = EL_DC_TIMEGATE_SWITCH;
5387       break;
5388
5389     case 0x168e:
5390       element = EL_ACID_POOL_BOTTOM;
5391       break;
5392
5393     case 0x168f:
5394       element = EL_ACID_POOL_TOPLEFT;
5395       break;
5396
5397     case 0x1690:
5398       element = EL_ACID_POOL_TOPRIGHT;
5399       break;
5400
5401     case 0x1691:
5402       element = EL_ACID_POOL_BOTTOMLEFT;
5403       break;
5404
5405     case 0x1692:
5406       element = EL_ACID_POOL_BOTTOMRIGHT;
5407       break;
5408
5409     case 0x1693:
5410       element = EL_STEELWALL;
5411       break;
5412
5413     case 0x1694:
5414       element = EL_STEELWALL_SLIPPERY;
5415       break;
5416
5417     case 0x1695:        // steel wall (not round)
5418       element = EL_STEELWALL;
5419       break;
5420
5421     case 0x1696:        // steel wall (left)
5422       element = EL_DC_STEELWALL_1_LEFT;
5423       break;
5424
5425     case 0x1697:        // steel wall (bottom)
5426       element = EL_DC_STEELWALL_1_BOTTOM;
5427       break;
5428
5429     case 0x1698:        // steel wall (right)
5430       element = EL_DC_STEELWALL_1_RIGHT;
5431       break;
5432
5433     case 0x1699:        // steel wall (top)
5434       element = EL_DC_STEELWALL_1_TOP;
5435       break;
5436
5437     case 0x169a:        // steel wall (left/bottom)
5438       element = EL_DC_STEELWALL_1_BOTTOMLEFT;
5439       break;
5440
5441     case 0x169b:        // steel wall (right/bottom)
5442       element = EL_DC_STEELWALL_1_BOTTOMRIGHT;
5443       break;
5444
5445     case 0x169c:        // steel wall (right/top)
5446       element = EL_DC_STEELWALL_1_TOPRIGHT;
5447       break;
5448
5449     case 0x169d:        // steel wall (left/top)
5450       element = EL_DC_STEELWALL_1_TOPLEFT;
5451       break;
5452
5453     case 0x169e:        // steel wall (right/bottom small)
5454       element = EL_DC_STEELWALL_1_BOTTOMRIGHT_2;
5455       break;
5456
5457     case 0x169f:        // steel wall (left/bottom small)
5458       element = EL_DC_STEELWALL_1_BOTTOMLEFT_2;
5459       break;
5460
5461     case 0x16a0:        // steel wall (right/top small)
5462       element = EL_DC_STEELWALL_1_TOPRIGHT_2;
5463       break;
5464
5465     case 0x16a1:        // steel wall (left/top small)
5466       element = EL_DC_STEELWALL_1_TOPLEFT_2;
5467       break;
5468
5469     case 0x16a2:        // steel wall (left/right)
5470       element = EL_DC_STEELWALL_1_VERTICAL;
5471       break;
5472
5473     case 0x16a3:        // steel wall (top/bottom)
5474       element = EL_DC_STEELWALL_1_HORIZONTAL;
5475       break;
5476
5477     case 0x16a4:        // steel wall 2 (left end)
5478       element = EL_DC_STEELWALL_2_LEFT;
5479       break;
5480
5481     case 0x16a5:        // steel wall 2 (right end)
5482       element = EL_DC_STEELWALL_2_RIGHT;
5483       break;
5484
5485     case 0x16a6:        // steel wall 2 (top end)
5486       element = EL_DC_STEELWALL_2_TOP;
5487       break;
5488
5489     case 0x16a7:        // steel wall 2 (bottom end)
5490       element = EL_DC_STEELWALL_2_BOTTOM;
5491       break;
5492
5493     case 0x16a8:        // steel wall 2 (left/right)
5494       element = EL_DC_STEELWALL_2_HORIZONTAL;
5495       break;
5496
5497     case 0x16a9:        // steel wall 2 (up/down)
5498       element = EL_DC_STEELWALL_2_VERTICAL;
5499       break;
5500
5501     case 0x16aa:        // steel wall 2 (mid)
5502       element = EL_DC_STEELWALL_2_MIDDLE;
5503       break;
5504
5505     case 0x16ab:
5506       element = EL_SIGN_EXCLAMATION;
5507       break;
5508
5509     case 0x16ac:
5510       element = EL_SIGN_RADIOACTIVITY;
5511       break;
5512
5513     case 0x16ad:
5514       element = EL_SIGN_STOP;
5515       break;
5516
5517     case 0x16ae:
5518       element = EL_SIGN_WHEELCHAIR;
5519       break;
5520
5521     case 0x16af:
5522       element = EL_SIGN_PARKING;
5523       break;
5524
5525     case 0x16b0:
5526       element = EL_SIGN_NO_ENTRY;
5527       break;
5528
5529     case 0x16b1:
5530       element = EL_SIGN_HEART;
5531       break;
5532
5533     case 0x16b2:
5534       element = EL_SIGN_GIVE_WAY;
5535       break;
5536
5537     case 0x16b3:
5538       element = EL_SIGN_ENTRY_FORBIDDEN;
5539       break;
5540
5541     case 0x16b4:
5542       element = EL_SIGN_EMERGENCY_EXIT;
5543       break;
5544
5545     case 0x16b5:
5546       element = EL_SIGN_YIN_YANG;
5547       break;
5548
5549     case 0x16b6:
5550       element = EL_WALL_EMERALD;
5551       break;
5552
5553     case 0x16b7:
5554       element = EL_WALL_DIAMOND;
5555       break;
5556
5557     case 0x16b8:
5558       element = EL_WALL_PEARL;
5559       break;
5560
5561     case 0x16b9:
5562       element = EL_WALL_CRYSTAL;
5563       break;
5564
5565     case 0x16ba:
5566       element = EL_INVISIBLE_WALL;
5567       break;
5568
5569     case 0x16bb:
5570       element = EL_INVISIBLE_STEELWALL;
5571       break;
5572
5573       // 0x16bc - 0x16cb:
5574       // EL_INVISIBLE_SAND
5575
5576     case 0x16cc:
5577       element = EL_LIGHT_SWITCH;
5578       break;
5579
5580     case 0x16cd:
5581       element = EL_ENVELOPE_1;
5582       break;
5583
5584     default:
5585       if (element >= 0x0117 && element <= 0x036e)       // (?)
5586         element = EL_DIAMOND;
5587       else if (element >= 0x042d && element <= 0x0684)  // (?)
5588         element = EL_EMERALD;
5589       else if (element >= 0x157c && element <= 0x158b)
5590         element = EL_SAND;
5591       else if (element >= 0x1590 && element <= 0x159f)
5592         element = EL_DC_LANDMINE;
5593       else if (element >= 0x16bc && element <= 0x16cb)
5594         element = EL_INVISIBLE_SAND;
5595       else
5596       {
5597         Warn("unknown Diamond Caves element 0x%04x", element);
5598
5599         element = EL_UNKNOWN;
5600       }
5601       break;
5602   }
5603
5604   return getMappedElement(element);
5605 }
5606
5607 static void LoadLevelFromFileStream_DC(File *file, struct LevelInfo *level,
5608                                        int nr)
5609 {
5610   byte header[DC_LEVEL_HEADER_SIZE];
5611   int envelope_size;
5612   int envelope_header_pos = 62;
5613   int envelope_content_pos = 94;
5614   int level_name_pos = 251;
5615   int level_author_pos = 292;
5616   int envelope_header_len;
5617   int envelope_content_len;
5618   int level_name_len;
5619   int level_author_len;
5620   int fieldx, fieldy;
5621   int num_yamyam_contents;
5622   int i, x, y;
5623
5624   getDecodedWord_DC(0, TRUE);           // initialize DC2 decoding engine
5625
5626   for (i = 0; i < DC_LEVEL_HEADER_SIZE / 2; i++)
5627   {
5628     unsigned short header_word = getDecodedWord_DC(getFile16BitBE(file), FALSE);
5629
5630     header[i * 2 + 0] = header_word >> 8;
5631     header[i * 2 + 1] = header_word & 0xff;
5632   }
5633
5634   // read some values from level header to check level decoding integrity
5635   fieldx = header[6] | (header[7] << 8);
5636   fieldy = header[8] | (header[9] << 8);
5637   num_yamyam_contents = header[60] | (header[61] << 8);
5638
5639   // do some simple sanity checks to ensure that level was correctly decoded
5640   if (fieldx < 1 || fieldx > 256 ||
5641       fieldy < 1 || fieldy > 256 ||
5642       num_yamyam_contents < 1 || num_yamyam_contents > 8)
5643   {
5644     level->no_valid_file = TRUE;
5645
5646     Warn("cannot decode level from stream -- using empty level");
5647
5648     return;
5649   }
5650
5651   // maximum envelope header size is 31 bytes
5652   envelope_header_len   = header[envelope_header_pos];
5653   // maximum envelope content size is 110 (156?) bytes
5654   envelope_content_len  = header[envelope_content_pos];
5655
5656   // maximum level title size is 40 bytes
5657   level_name_len        = MIN(header[level_name_pos],   MAX_LEVEL_NAME_LEN);
5658   // maximum level author size is 30 (51?) bytes
5659   level_author_len      = MIN(header[level_author_pos], MAX_LEVEL_AUTHOR_LEN);
5660
5661   envelope_size = 0;
5662
5663   for (i = 0; i < envelope_header_len; i++)
5664     if (envelope_size < MAX_ENVELOPE_TEXT_LEN)
5665       level->envelope[0].text[envelope_size++] =
5666         header[envelope_header_pos + 1 + i];
5667
5668   if (envelope_header_len > 0 && envelope_content_len > 0)
5669   {
5670     if (envelope_size < MAX_ENVELOPE_TEXT_LEN)
5671       level->envelope[0].text[envelope_size++] = '\n';
5672     if (envelope_size < MAX_ENVELOPE_TEXT_LEN)
5673       level->envelope[0].text[envelope_size++] = '\n';
5674   }
5675
5676   for (i = 0; i < envelope_content_len; i++)
5677     if (envelope_size < MAX_ENVELOPE_TEXT_LEN)
5678       level->envelope[0].text[envelope_size++] =
5679         header[envelope_content_pos + 1 + i];
5680
5681   level->envelope[0].text[envelope_size] = '\0';
5682
5683   level->envelope[0].xsize = MAX_ENVELOPE_XSIZE;
5684   level->envelope[0].ysize = 10;
5685   level->envelope[0].autowrap = TRUE;
5686   level->envelope[0].centered = TRUE;
5687
5688   for (i = 0; i < level_name_len; i++)
5689     level->name[i] = header[level_name_pos + 1 + i];
5690   level->name[level_name_len] = '\0';
5691
5692   for (i = 0; i < level_author_len; i++)
5693     level->author[i] = header[level_author_pos + 1 + i];
5694   level->author[level_author_len] = '\0';
5695
5696   num_yamyam_contents = header[60] | (header[61] << 8);
5697   level->num_yamyam_contents =
5698     MIN(MAX(MIN_ELEMENT_CONTENTS, num_yamyam_contents), MAX_ELEMENT_CONTENTS);
5699
5700   for (i = 0; i < num_yamyam_contents; i++)
5701   {
5702     for (y = 0; y < 3; y++) for (x = 0; x < 3; x++)
5703     {
5704       unsigned short word = getDecodedWord_DC(getFile16BitBE(file), FALSE);
5705       int element_dc = ((word & 0xff) << 8) | ((word >> 8) & 0xff);
5706
5707       if (i < MAX_ELEMENT_CONTENTS)
5708         level->yamyam_content[i].e[x][y] = getMappedElement_DC(element_dc);
5709     }
5710   }
5711
5712   fieldx = header[6] | (header[7] << 8);
5713   fieldy = header[8] | (header[9] << 8);
5714   level->fieldx = MIN(MAX(MIN_LEV_FIELDX, fieldx), MAX_LEV_FIELDX);
5715   level->fieldy = MIN(MAX(MIN_LEV_FIELDY, fieldy), MAX_LEV_FIELDY);
5716
5717   for (y = 0; y < fieldy; y++) for (x = 0; x < fieldx; x++)
5718   {
5719     unsigned short word = getDecodedWord_DC(getFile16BitBE(file), FALSE);
5720     int element_dc = ((word & 0xff) << 8) | ((word >> 8) & 0xff);
5721
5722     if (x < MAX_LEV_FIELDX && y < MAX_LEV_FIELDY)
5723       level->field[x][y] = getMappedElement_DC(element_dc);
5724   }
5725
5726   x = MIN(MAX(0, (header[10] | (header[11] << 8)) - 1), MAX_LEV_FIELDX - 1);
5727   y = MIN(MAX(0, (header[12] | (header[13] << 8)) - 1), MAX_LEV_FIELDY - 1);
5728   level->field[x][y] = EL_PLAYER_1;
5729
5730   x = MIN(MAX(0, (header[14] | (header[15] << 8)) - 1), MAX_LEV_FIELDX - 1);
5731   y = MIN(MAX(0, (header[16] | (header[17] << 8)) - 1), MAX_LEV_FIELDY - 1);
5732   level->field[x][y] = EL_PLAYER_2;
5733
5734   level->gems_needed            = header[18] | (header[19] << 8);
5735
5736   level->score[SC_EMERALD]      = header[20] | (header[21] << 8);
5737   level->score[SC_DIAMOND]      = header[22] | (header[23] << 8);
5738   level->score[SC_PEARL]        = header[24] | (header[25] << 8);
5739   level->score[SC_CRYSTAL]      = header[26] | (header[27] << 8);
5740   level->score[SC_NUT]          = header[28] | (header[29] << 8);
5741   level->score[SC_ROBOT]        = header[30] | (header[31] << 8);
5742   level->score[SC_SPACESHIP]    = header[32] | (header[33] << 8);
5743   level->score[SC_BUG]          = header[34] | (header[35] << 8);
5744   level->score[SC_YAMYAM]       = header[36] | (header[37] << 8);
5745   level->score[SC_DYNAMITE]     = header[38] | (header[39] << 8);
5746   level->score[SC_KEY]          = header[40] | (header[41] << 8);
5747   level->score[SC_TIME_BONUS]   = header[42] | (header[43] << 8);
5748
5749   level->time                   = header[44] | (header[45] << 8);
5750
5751   level->amoeba_speed           = header[46] | (header[47] << 8);
5752   level->time_light             = header[48] | (header[49] << 8);
5753   level->time_timegate          = header[50] | (header[51] << 8);
5754   level->time_wheel             = header[52] | (header[53] << 8);
5755   level->time_magic_wall        = header[54] | (header[55] << 8);
5756   level->extra_time             = header[56] | (header[57] << 8);
5757   level->shield_normal_time     = header[58] | (header[59] << 8);
5758
5759   // shield and extra time elements do not have a score
5760   level->score[SC_SHIELD]       = 0;
5761   level->extra_time_score       = 0;
5762
5763   // set time for normal and deadly shields to the same value
5764   level->shield_deadly_time     = level->shield_normal_time;
5765
5766   // Diamond Caves has the same (strange) behaviour as Emerald Mine that gems
5767   // can slip down from flat walls, like normal walls and steel walls
5768   level->em_slippery_gems = TRUE;
5769
5770   // time score is counted for each 10 seconds left in Diamond Caves levels
5771   level->time_score_base = 10;
5772 }
5773
5774 static void LoadLevelFromFileInfo_DC(struct LevelInfo *level,
5775                                      struct LevelFileInfo *level_file_info,
5776                                      boolean level_info_only)
5777 {
5778   char *filename = level_file_info->filename;
5779   File *file;
5780   int num_magic_bytes = 8;
5781   char magic_bytes[num_magic_bytes + 1];
5782   int num_levels_to_skip = level_file_info->nr - leveldir_current->first_level;
5783
5784   if (!(file = openFile(filename, MODE_READ)))
5785   {
5786     level->no_valid_file = TRUE;
5787
5788     if (!level_info_only)
5789       Warn("cannot read level '%s' -- using empty level", filename);
5790
5791     return;
5792   }
5793
5794   // fseek(file, 0x0000, SEEK_SET);
5795
5796   if (level_file_info->packed)
5797   {
5798     // read "magic bytes" from start of file
5799     if (getStringFromFile(file, magic_bytes, num_magic_bytes + 1) == NULL)
5800       magic_bytes[0] = '\0';
5801
5802     // check "magic bytes" for correct file format
5803     if (!strPrefix(magic_bytes, "DC2"))
5804     {
5805       level->no_valid_file = TRUE;
5806
5807       Warn("unknown DC level file '%s' -- using empty level", filename);
5808
5809       return;
5810     }
5811
5812     if (strPrefix(magic_bytes, "DC2Win95") ||
5813         strPrefix(magic_bytes, "DC2Win98"))
5814     {
5815       int position_first_level = 0x00fa;
5816       int extra_bytes = 4;
5817       int skip_bytes;
5818
5819       // advance file stream to first level inside the level package
5820       skip_bytes = position_first_level - num_magic_bytes - extra_bytes;
5821
5822       // each block of level data is followed by block of non-level data
5823       num_levels_to_skip *= 2;
5824
5825       // at least skip header bytes, therefore use ">= 0" instead of "> 0"
5826       while (num_levels_to_skip >= 0)
5827       {
5828         // advance file stream to next level inside the level package
5829         if (seekFile(file, skip_bytes, SEEK_CUR) != 0)
5830         {
5831           level->no_valid_file = TRUE;
5832
5833           Warn("cannot fseek in file '%s' -- using empty level", filename);
5834
5835           return;
5836         }
5837
5838         // skip apparently unused extra bytes following each level
5839         ReadUnusedBytesFromFile(file, extra_bytes);
5840
5841         // read size of next level in level package
5842         skip_bytes = getFile32BitLE(file);
5843
5844         num_levels_to_skip--;
5845       }
5846     }
5847     else
5848     {
5849       level->no_valid_file = TRUE;
5850
5851       Warn("unknown DC2 level file '%s' -- using empty level", filename);
5852
5853       return;
5854     }
5855   }
5856
5857   LoadLevelFromFileStream_DC(file, level, level_file_info->nr);
5858
5859   closeFile(file);
5860 }
5861
5862
5863 // ----------------------------------------------------------------------------
5864 // functions for loading SB level
5865 // ----------------------------------------------------------------------------
5866
5867 int getMappedElement_SB(int element_ascii, boolean use_ces)
5868 {
5869   static struct
5870   {
5871     int ascii;
5872     int sb;
5873     int ce;
5874   }
5875   sb_element_mapping[] =
5876   {
5877     { ' ', EL_EMPTY,                EL_CUSTOM_1 },  // floor (space)
5878     { '#', EL_STEELWALL,            EL_CUSTOM_2 },  // wall
5879     { '@', EL_PLAYER_1,             EL_CUSTOM_3 },  // player
5880     { '$', EL_SOKOBAN_OBJECT,       EL_CUSTOM_4 },  // box
5881     { '.', EL_SOKOBAN_FIELD_EMPTY,  EL_CUSTOM_5 },  // goal square
5882     { '*', EL_SOKOBAN_FIELD_FULL,   EL_CUSTOM_6 },  // box on goal square
5883     { '+', EL_SOKOBAN_FIELD_PLAYER, EL_CUSTOM_7 },  // player on goal square
5884     { '_', EL_INVISIBLE_STEELWALL,  EL_FROM_LEVEL_TEMPLATE },  // floor beyond border
5885
5886     { 0,   -1,                      -1          },
5887   };
5888
5889   int i;
5890
5891   for (i = 0; sb_element_mapping[i].ascii != 0; i++)
5892     if (element_ascii == sb_element_mapping[i].ascii)
5893       return (use_ces ? sb_element_mapping[i].ce : sb_element_mapping[i].sb);
5894
5895   return EL_UNDEFINED;
5896 }
5897
5898 static void LoadLevelFromFileInfo_SB(struct LevelInfo *level,
5899                                      struct LevelFileInfo *level_file_info,
5900                                      boolean level_info_only)
5901 {
5902   char *filename = level_file_info->filename;
5903   char line[MAX_LINE_LEN], line_raw[MAX_LINE_LEN], previous_line[MAX_LINE_LEN];
5904   char last_comment[MAX_LINE_LEN];
5905   char level_name[MAX_LINE_LEN];
5906   char *line_ptr;
5907   File *file;
5908   int num_levels_to_skip = level_file_info->nr - leveldir_current->first_level;
5909   boolean read_continued_line = FALSE;
5910   boolean reading_playfield = FALSE;
5911   boolean got_valid_playfield_line = FALSE;
5912   boolean invalid_playfield_char = FALSE;
5913   boolean load_xsb_to_ces = check_special_flags("load_xsb_to_ces");
5914   int file_level_nr = 0;
5915   int line_nr = 0;
5916   int x = 0, y = 0;             // initialized to make compilers happy
5917
5918   last_comment[0] = '\0';
5919   level_name[0] = '\0';
5920
5921   if (!(file = openFile(filename, MODE_READ)))
5922   {
5923     level->no_valid_file = TRUE;
5924
5925     if (!level_info_only)
5926       Warn("cannot read level '%s' -- using empty level", filename);
5927
5928     return;
5929   }
5930
5931   while (!checkEndOfFile(file))
5932   {
5933     // level successfully read, but next level may follow here
5934     if (!got_valid_playfield_line && reading_playfield)
5935     {
5936       // read playfield from single level file -- skip remaining file
5937       if (!level_file_info->packed)
5938         break;
5939
5940       if (file_level_nr >= num_levels_to_skip)
5941         break;
5942
5943       file_level_nr++;
5944
5945       last_comment[0] = '\0';
5946       level_name[0] = '\0';
5947
5948       reading_playfield = FALSE;
5949     }
5950
5951     got_valid_playfield_line = FALSE;
5952
5953     // read next line of input file
5954     if (!getStringFromFile(file, line, MAX_LINE_LEN))
5955       break;
5956
5957     // check if line was completely read and is terminated by line break
5958     if (strlen(line) > 0 && line[strlen(line) - 1] == '\n')
5959       line_nr++;
5960
5961     // cut trailing line break (this can be newline and/or carriage return)
5962     for (line_ptr = &line[strlen(line)]; line_ptr >= line; line_ptr--)
5963       if ((*line_ptr == '\n' || *line_ptr == '\r') && *(line_ptr + 1) == '\0')
5964         *line_ptr = '\0';
5965
5966     // copy raw input line for later use (mainly debugging output)
5967     strcpy(line_raw, line);
5968
5969     if (read_continued_line)
5970     {
5971       // append new line to existing line, if there is enough space
5972       if (strlen(previous_line) + strlen(line_ptr) < MAX_LINE_LEN)
5973         strcat(previous_line, line_ptr);
5974
5975       strcpy(line, previous_line);      // copy storage buffer to line
5976
5977       read_continued_line = FALSE;
5978     }
5979
5980     // if the last character is '\', continue at next line
5981     if (strlen(line) > 0 && line[strlen(line) - 1] == '\\')
5982     {
5983       line[strlen(line) - 1] = '\0';    // cut off trailing backslash
5984       strcpy(previous_line, line);      // copy line to storage buffer
5985
5986       read_continued_line = TRUE;
5987
5988       continue;
5989     }
5990
5991     // skip empty lines
5992     if (line[0] == '\0')
5993       continue;
5994
5995     // extract comment text from comment line
5996     if (line[0] == ';')
5997     {
5998       for (line_ptr = line; *line_ptr; line_ptr++)
5999         if (*line_ptr != ' ' && *line_ptr != '\t' && *line_ptr != ';')
6000           break;
6001
6002       strcpy(last_comment, line_ptr);
6003
6004       continue;
6005     }
6006
6007     // extract level title text from line containing level title
6008     if (line[0] == '\'')
6009     {
6010       strcpy(level_name, &line[1]);
6011
6012       if (strlen(level_name) > 0 && level_name[strlen(level_name) - 1] == '\'')
6013         level_name[strlen(level_name) - 1] = '\0';
6014
6015       continue;
6016     }
6017
6018     // skip lines containing only spaces (or empty lines)
6019     for (line_ptr = line; *line_ptr; line_ptr++)
6020       if (*line_ptr != ' ')
6021         break;
6022     if (*line_ptr == '\0')
6023       continue;
6024
6025     // at this point, we have found a line containing part of a playfield
6026
6027     got_valid_playfield_line = TRUE;
6028
6029     if (!reading_playfield)
6030     {
6031       reading_playfield = TRUE;
6032       invalid_playfield_char = FALSE;
6033
6034       for (x = 0; x < MAX_LEV_FIELDX; x++)
6035         for (y = 0; y < MAX_LEV_FIELDY; y++)
6036           level->field[x][y] = getMappedElement_SB(' ', load_xsb_to_ces);
6037
6038       level->fieldx = 0;
6039       level->fieldy = 0;
6040
6041       // start with topmost tile row
6042       y = 0;
6043     }
6044
6045     // skip playfield line if larger row than allowed
6046     if (y >= MAX_LEV_FIELDY)
6047       continue;
6048
6049     // start with leftmost tile column
6050     x = 0;
6051
6052     // read playfield elements from line
6053     for (line_ptr = line; *line_ptr; line_ptr++)
6054     {
6055       int mapped_sb_element = getMappedElement_SB(*line_ptr, load_xsb_to_ces);
6056
6057       // stop parsing playfield line if larger column than allowed
6058       if (x >= MAX_LEV_FIELDX)
6059         break;
6060
6061       if (mapped_sb_element == EL_UNDEFINED)
6062       {
6063         invalid_playfield_char = TRUE;
6064
6065         break;
6066       }
6067
6068       level->field[x][y] = mapped_sb_element;
6069
6070       // continue with next tile column
6071       x++;
6072
6073       level->fieldx = MAX(x, level->fieldx);
6074     }
6075
6076     if (invalid_playfield_char)
6077     {
6078       // if first playfield line, treat invalid lines as comment lines
6079       if (y == 0)
6080         reading_playfield = FALSE;
6081
6082       continue;
6083     }
6084
6085     // continue with next tile row
6086     y++;
6087   }
6088
6089   closeFile(file);
6090
6091   level->fieldy = y;
6092
6093   level->fieldx = MIN(MAX(MIN_LEV_FIELDX, level->fieldx), MAX_LEV_FIELDX);
6094   level->fieldy = MIN(MAX(MIN_LEV_FIELDY, level->fieldy), MAX_LEV_FIELDY);
6095
6096   if (!reading_playfield)
6097   {
6098     level->no_valid_file = TRUE;
6099
6100     Warn("cannot read level '%s' -- using empty level", filename);
6101
6102     return;
6103   }
6104
6105   if (*level_name != '\0')
6106   {
6107     strncpy(level->name, level_name, MAX_LEVEL_NAME_LEN);
6108     level->name[MAX_LEVEL_NAME_LEN] = '\0';
6109   }
6110   else if (*last_comment != '\0')
6111   {
6112     strncpy(level->name, last_comment, MAX_LEVEL_NAME_LEN);
6113     level->name[MAX_LEVEL_NAME_LEN] = '\0';
6114   }
6115   else
6116   {
6117     sprintf(level->name, "--> Level %d <--", level_file_info->nr);
6118   }
6119
6120   // set all empty fields beyond the border walls to invisible steel wall
6121   for (y = 0; y < level->fieldy; y++) for (x = 0; x < level->fieldx; x++)
6122   {
6123     if ((x == 0 || x == level->fieldx - 1 ||
6124          y == 0 || y == level->fieldy - 1) &&
6125         level->field[x][y] == getMappedElement_SB(' ', load_xsb_to_ces))
6126       FloodFillLevel(x, y, getMappedElement_SB('_', load_xsb_to_ces),
6127                      level->field, level->fieldx, level->fieldy);
6128   }
6129
6130   // set special level settings for Sokoban levels
6131
6132   level->time = 0;
6133   level->use_step_counter = TRUE;
6134   level->auto_exit_sokoban = TRUE;
6135
6136   if (load_xsb_to_ces)
6137   {
6138     // special global settings can now be set in level template
6139
6140     level->use_custom_template = TRUE;
6141   }
6142 }
6143
6144
6145 // -------------------------------------------------------------------------
6146 // functions for handling native levels
6147 // -------------------------------------------------------------------------
6148
6149 static void LoadLevelFromFileInfo_EM(struct LevelInfo *level,
6150                                      struct LevelFileInfo *level_file_info,
6151                                      boolean level_info_only)
6152 {
6153   if (!LoadNativeLevel_EM(level_file_info->filename, level_info_only))
6154     level->no_valid_file = TRUE;
6155 }
6156
6157 static void LoadLevelFromFileInfo_SP(struct LevelInfo *level,
6158                                      struct LevelFileInfo *level_file_info,
6159                                      boolean level_info_only)
6160 {
6161   int pos = 0;
6162
6163   // determine position of requested level inside level package
6164   if (level_file_info->packed)
6165     pos = level_file_info->nr - leveldir_current->first_level;
6166
6167   if (!LoadNativeLevel_SP(level_file_info->filename, pos, level_info_only))
6168     level->no_valid_file = TRUE;
6169 }
6170
6171 static void LoadLevelFromFileInfo_MM(struct LevelInfo *level,
6172                                      struct LevelFileInfo *level_file_info,
6173                                      boolean level_info_only)
6174 {
6175   if (!LoadNativeLevel_MM(level_file_info->filename, level_info_only))
6176     level->no_valid_file = TRUE;
6177 }
6178
6179 void CopyNativeLevel_RND_to_Native(struct LevelInfo *level)
6180 {
6181   if (level->game_engine_type == GAME_ENGINE_TYPE_EM)
6182     CopyNativeLevel_RND_to_EM(level);
6183   else if (level->game_engine_type == GAME_ENGINE_TYPE_SP)
6184     CopyNativeLevel_RND_to_SP(level);
6185   else if (level->game_engine_type == GAME_ENGINE_TYPE_MM)
6186     CopyNativeLevel_RND_to_MM(level);
6187 }
6188
6189 void CopyNativeLevel_Native_to_RND(struct LevelInfo *level)
6190 {
6191   if (level->game_engine_type == GAME_ENGINE_TYPE_EM)
6192     CopyNativeLevel_EM_to_RND(level);
6193   else if (level->game_engine_type == GAME_ENGINE_TYPE_SP)
6194     CopyNativeLevel_SP_to_RND(level);
6195   else if (level->game_engine_type == GAME_ENGINE_TYPE_MM)
6196     CopyNativeLevel_MM_to_RND(level);
6197 }
6198
6199 void SaveNativeLevel(struct LevelInfo *level)
6200 {
6201   if (level->game_engine_type == GAME_ENGINE_TYPE_SP)
6202   {
6203     char *basename = getSingleLevelBasenameExt(level->file_info.nr, "sp");
6204     char *filename = getLevelFilenameFromBasename(basename);
6205
6206     CopyNativeLevel_RND_to_SP(level);
6207     CopyNativeTape_RND_to_SP(level);
6208
6209     SaveNativeLevel_SP(filename);
6210   }
6211 }
6212
6213
6214 // ----------------------------------------------------------------------------
6215 // functions for loading generic level
6216 // ----------------------------------------------------------------------------
6217
6218 static void LoadLevelFromFileInfo(struct LevelInfo *level,
6219                                   struct LevelFileInfo *level_file_info,
6220                                   boolean level_info_only)
6221 {
6222   // always start with reliable default values
6223   setLevelInfoToDefaults(level, level_info_only, TRUE);
6224
6225   switch (level_file_info->type)
6226   {
6227     case LEVEL_FILE_TYPE_RND:
6228       LoadLevelFromFileInfo_RND(level, level_file_info, level_info_only);
6229       break;
6230
6231     case LEVEL_FILE_TYPE_EM:
6232       LoadLevelFromFileInfo_EM(level, level_file_info, level_info_only);
6233       level->game_engine_type = GAME_ENGINE_TYPE_EM;
6234       break;
6235
6236     case LEVEL_FILE_TYPE_SP:
6237       LoadLevelFromFileInfo_SP(level, level_file_info, level_info_only);
6238       level->game_engine_type = GAME_ENGINE_TYPE_SP;
6239       break;
6240
6241     case LEVEL_FILE_TYPE_MM:
6242       LoadLevelFromFileInfo_MM(level, level_file_info, level_info_only);
6243       level->game_engine_type = GAME_ENGINE_TYPE_MM;
6244       break;
6245
6246     case LEVEL_FILE_TYPE_DC:
6247       LoadLevelFromFileInfo_DC(level, level_file_info, level_info_only);
6248       break;
6249
6250     case LEVEL_FILE_TYPE_SB:
6251       LoadLevelFromFileInfo_SB(level, level_file_info, level_info_only);
6252       break;
6253
6254     default:
6255       LoadLevelFromFileInfo_RND(level, level_file_info, level_info_only);
6256       break;
6257   }
6258
6259   // if level file is invalid, restore level structure to default values
6260   if (level->no_valid_file)
6261     setLevelInfoToDefaults(level, level_info_only, FALSE);
6262
6263   if (level->game_engine_type == GAME_ENGINE_TYPE_UNKNOWN)
6264     level->game_engine_type = GAME_ENGINE_TYPE_RND;
6265
6266   if (level_file_info->type != LEVEL_FILE_TYPE_RND)
6267     CopyNativeLevel_Native_to_RND(level);
6268 }
6269
6270 void LoadLevelFromFilename(struct LevelInfo *level, char *filename)
6271 {
6272   static struct LevelFileInfo level_file_info;
6273
6274   // always start with reliable default values
6275   setFileInfoToDefaults(&level_file_info);
6276
6277   level_file_info.nr = 0;                       // unknown level number
6278   level_file_info.type = LEVEL_FILE_TYPE_RND;   // no others supported yet
6279
6280   setString(&level_file_info.filename, filename);
6281
6282   LoadLevelFromFileInfo(level, &level_file_info, FALSE);
6283 }
6284
6285 static void LoadLevel_InitVersion(struct LevelInfo *level)
6286 {
6287   int i, j;
6288
6289   if (leveldir_current == NULL)         // only when dumping level
6290     return;
6291
6292   // all engine modifications also valid for levels which use latest engine
6293   if (level->game_version < VERSION_IDENT(3,2,0,5))
6294   {
6295     // time bonus score was given for 10 s instead of 1 s before 3.2.0-5
6296     level->time_score_base = 10;
6297   }
6298
6299   if (leveldir_current->latest_engine)
6300   {
6301     // ---------- use latest game engine --------------------------------------
6302
6303     /* For all levels which are forced to use the latest game engine version
6304        (normally all but user contributed, private and undefined levels), set
6305        the game engine version to the actual version; this allows for actual
6306        corrections in the game engine to take effect for existing, converted
6307        levels (from "classic" or other existing games) to make the emulation
6308        of the corresponding game more accurate, while (hopefully) not breaking
6309        existing levels created from other players. */
6310
6311     level->game_version = GAME_VERSION_ACTUAL;
6312
6313     /* Set special EM style gems behaviour: EM style gems slip down from
6314        normal, steel and growing wall. As this is a more fundamental change,
6315        it seems better to set the default behaviour to "off" (as it is more
6316        natural) and make it configurable in the level editor (as a property
6317        of gem style elements). Already existing converted levels (neither
6318        private nor contributed levels) are changed to the new behaviour. */
6319
6320     if (level->file_version < FILE_VERSION_2_0)
6321       level->em_slippery_gems = TRUE;
6322
6323     return;
6324   }
6325
6326   // ---------- use game engine the level was created with --------------------
6327
6328   /* For all levels which are not forced to use the latest game engine
6329      version (normally user contributed, private and undefined levels),
6330      use the version of the game engine the levels were created for.
6331
6332      Since 2.0.1, the game engine version is now directly stored
6333      in the level file (chunk "VERS"), so there is no need anymore
6334      to set the game version from the file version (except for old,
6335      pre-2.0 levels, where the game version is still taken from the
6336      file format version used to store the level -- see above). */
6337
6338   // player was faster than enemies in 1.0.0 and before
6339   if (level->file_version == FILE_VERSION_1_0)
6340     for (i = 0; i < MAX_PLAYERS; i++)
6341       level->initial_player_stepsize[i] = STEPSIZE_FAST;
6342
6343   // default behaviour for EM style gems was "slippery" only in 2.0.1
6344   if (level->game_version == VERSION_IDENT(2,0,1,0))
6345     level->em_slippery_gems = TRUE;
6346
6347   // springs could be pushed over pits before (pre-release version) 2.2.0
6348   if (level->game_version < VERSION_IDENT(2,2,0,0))
6349     level->use_spring_bug = TRUE;
6350
6351   if (level->game_version < VERSION_IDENT(3,2,0,5))
6352   {
6353     // time orb caused limited time in endless time levels before 3.2.0-5
6354     level->use_time_orb_bug = TRUE;
6355
6356     // default behaviour for snapping was "no snap delay" before 3.2.0-5
6357     level->block_snap_field = FALSE;
6358
6359     // extra time score was same value as time left score before 3.2.0-5
6360     level->extra_time_score = level->score[SC_TIME_BONUS];
6361   }
6362
6363   if (level->game_version < VERSION_IDENT(3,2,0,7))
6364   {
6365     // default behaviour for snapping was "not continuous" before 3.2.0-7
6366     level->continuous_snapping = FALSE;
6367   }
6368
6369   // only few elements were able to actively move into acid before 3.1.0
6370   // trigger settings did not exist before 3.1.0; set to default "any"
6371   if (level->game_version < VERSION_IDENT(3,1,0,0))
6372   {
6373     // correct "can move into acid" settings (all zero in old levels)
6374
6375     level->can_move_into_acid_bits = 0; // nothing can move into acid
6376     level->dont_collide_with_bits = 0; // nothing is deadly when colliding
6377
6378     setMoveIntoAcidProperty(level, EL_ROBOT,     TRUE);
6379     setMoveIntoAcidProperty(level, EL_SATELLITE, TRUE);
6380     setMoveIntoAcidProperty(level, EL_PENGUIN,   TRUE);
6381     setMoveIntoAcidProperty(level, EL_BALLOON,   TRUE);
6382
6383     for (i = 0; i < NUM_CUSTOM_ELEMENTS; i++)
6384       SET_PROPERTY(EL_CUSTOM_START + i, EP_CAN_MOVE_INTO_ACID, TRUE);
6385
6386     // correct trigger settings (stored as zero == "none" in old levels)
6387
6388     for (i = 0; i < NUM_CUSTOM_ELEMENTS; i++)
6389     {
6390       int element = EL_CUSTOM_START + i;
6391       struct ElementInfo *ei = &element_info[element];
6392
6393       for (j = 0; j < ei->num_change_pages; j++)
6394       {
6395         struct ElementChangeInfo *change = &ei->change_page[j];
6396
6397         change->trigger_player = CH_PLAYER_ANY;
6398         change->trigger_page = CH_PAGE_ANY;
6399       }
6400     }
6401   }
6402
6403   // try to detect and fix "Snake Bite" levels, which are broken with 3.2.0
6404   {
6405     int element = EL_CUSTOM_256;
6406     struct ElementInfo *ei = &element_info[element];
6407     struct ElementChangeInfo *change = &ei->change_page[0];
6408
6409     /* This is needed to fix a problem that was caused by a bugfix in function
6410        game.c/CreateFieldExt() introduced with 3.2.0 that corrects the behaviour
6411        when a custom element changes to EL_SOKOBAN_FIELD_PLAYER (before, it did
6412        not replace walkable elements, but instead just placed the player on it,
6413        without placing the Sokoban field under the player). Unfortunately, this
6414        breaks "Snake Bite" style levels when the snake is halfway through a door
6415        that just closes (the snake head is still alive and can be moved in this
6416        case). This can be fixed by replacing the EL_SOKOBAN_FIELD_PLAYER by the
6417        player (without Sokoban element) which then gets killed as designed). */
6418
6419     if ((strncmp(leveldir_current->identifier, "snake_bite", 10) == 0 ||
6420          strncmp(ei->description, "pause b4 death", 14) == 0) &&
6421         change->target_element == EL_SOKOBAN_FIELD_PLAYER)
6422       change->target_element = EL_PLAYER_1;
6423   }
6424
6425   // try to detect and fix "Zelda" style levels, which are broken with 3.2.5
6426   if (level->game_version < VERSION_IDENT(3,2,5,0))
6427   {
6428     /* This is needed to fix a problem that was caused by a bugfix in function
6429        game.c/CheckTriggeredElementChangeExt() introduced with 3.2.5 that
6430        corrects the behaviour when a custom element changes to another custom
6431        element with a higher element number that has change actions defined.
6432        Normally, only one change per frame is allowed for custom elements.
6433        Therefore, it is checked if a custom element already changed in the
6434        current frame; if it did, subsequent changes are suppressed.
6435        Unfortunately, this is only checked for element changes, but not for
6436        change actions, which are still executed. As the function above loops
6437        through all custom elements from lower to higher, an element change
6438        resulting in a lower CE number won't be checked again, while a target
6439        element with a higher number will also be checked, and potential change
6440        actions will get executed for this CE, too (which is wrong), while
6441        further changes are ignored (which is correct). As this bugfix breaks
6442        Zelda II (and introduces graphical bugs to Zelda I, and also breaks a
6443        few other levels like Alan Bond's "FMV"), allow the previous, incorrect
6444        behaviour for existing levels and tapes that make use of this bug */
6445
6446     level->use_action_after_change_bug = TRUE;
6447   }
6448
6449   // not centering level after relocating player was default only in 3.2.3
6450   if (level->game_version == VERSION_IDENT(3,2,3,0))    // (no pre-releases)
6451     level->shifted_relocation = TRUE;
6452
6453   // EM style elements always chain-exploded in R'n'D engine before 3.2.6
6454   if (level->game_version < VERSION_IDENT(3,2,6,0))
6455     level->em_explodes_by_fire = TRUE;
6456
6457   // levels were solved by the first player entering an exit up to 4.1.0.0
6458   if (level->game_version <= VERSION_IDENT(4,1,0,0))
6459     level->solved_by_one_player = TRUE;
6460
6461   // game logic of "game of life" and "biomaze" was buggy before 4.1.1.1
6462   if (level->game_version < VERSION_IDENT(4,1,1,1))
6463     level->use_life_bugs = TRUE;
6464
6465   // only Sokoban fields (but not objects) had to be solved before 4.1.1.1
6466   if (level->game_version < VERSION_IDENT(4,1,1,1))
6467     level->sb_objects_needed = FALSE;
6468
6469   // CE actions were triggered by unfinished digging/collecting up to 4.2.2.0
6470   if (level->game_version <= VERSION_IDENT(4,2,2,0))
6471     level->finish_dig_collect = FALSE;
6472
6473   // CE changing to player was kept under the player if walkable up to 4.2.3.1
6474   if (level->game_version <= VERSION_IDENT(4,2,3,1))
6475     level->keep_walkable_ce = TRUE;
6476 }
6477
6478 static void LoadLevel_InitSettings_SB(struct LevelInfo *level)
6479 {
6480   boolean is_sokoban_level = TRUE;    // unless non-Sokoban elements found
6481   int x, y;
6482
6483   // check if this level is (not) a Sokoban level
6484   for (y = 0; y < level->fieldy; y++)
6485     for (x = 0; x < level->fieldx; x++)
6486       if (!IS_SB_ELEMENT(Tile[x][y]))
6487         is_sokoban_level = FALSE;
6488
6489   if (is_sokoban_level)
6490   {
6491     // set special level settings for Sokoban levels
6492     level->time = 0;
6493     level->use_step_counter = TRUE;
6494     level->auto_exit_sokoban = TRUE;
6495   }
6496 }
6497
6498 static void LoadLevel_InitSettings(struct LevelInfo *level)
6499 {
6500   // adjust level settings for (non-native) Sokoban-style levels
6501   LoadLevel_InitSettings_SB(level);
6502 }
6503
6504 static void LoadLevel_InitStandardElements(struct LevelInfo *level)
6505 {
6506   int i, x, y;
6507
6508   // map elements that have changed in newer versions
6509   level->amoeba_content = getMappedElementByVersion(level->amoeba_content,
6510                                                     level->game_version);
6511   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
6512     for (x = 0; x < 3; x++)
6513       for (y = 0; y < 3; y++)
6514         level->yamyam_content[i].e[x][y] =
6515           getMappedElementByVersion(level->yamyam_content[i].e[x][y],
6516                                     level->game_version);
6517
6518 }
6519
6520 static void LoadLevel_InitCustomElements(struct LevelInfo *level)
6521 {
6522   int i, j;
6523
6524   // map custom element change events that have changed in newer versions
6525   // (these following values were accidentally changed in version 3.0.1)
6526   // (this seems to be needed only for 'ab_levelset3' and 'ab_levelset4')
6527   if (level->game_version <= VERSION_IDENT(3,0,0,0))
6528   {
6529     for (i = 0; i < NUM_CUSTOM_ELEMENTS; i++)
6530     {
6531       int element = EL_CUSTOM_START + i;
6532
6533       // order of checking and copying events to be mapped is important
6534       // (do not change the start and end value -- they are constant)
6535       for (j = CE_BY_OTHER_ACTION; j >= CE_VALUE_GETS_ZERO; j--)
6536       {
6537         if (HAS_CHANGE_EVENT(element, j - 2))
6538         {
6539           SET_CHANGE_EVENT(element, j - 2, FALSE);
6540           SET_CHANGE_EVENT(element, j, TRUE);
6541         }
6542       }
6543
6544       // order of checking and copying events to be mapped is important
6545       // (do not change the start and end value -- they are constant)
6546       for (j = CE_PLAYER_COLLECTS_X; j >= CE_HITTING_SOMETHING; j--)
6547       {
6548         if (HAS_CHANGE_EVENT(element, j - 1))
6549         {
6550           SET_CHANGE_EVENT(element, j - 1, FALSE);
6551           SET_CHANGE_EVENT(element, j, TRUE);
6552         }
6553       }
6554     }
6555   }
6556
6557   // initialize "can_change" field for old levels with only one change page
6558   if (level->game_version <= VERSION_IDENT(3,0,2,0))
6559   {
6560     for (i = 0; i < NUM_CUSTOM_ELEMENTS; i++)
6561     {
6562       int element = EL_CUSTOM_START + i;
6563
6564       if (CAN_CHANGE(element))
6565         element_info[element].change->can_change = TRUE;
6566     }
6567   }
6568
6569   // correct custom element values (for old levels without these options)
6570   if (level->game_version < VERSION_IDENT(3,1,1,0))
6571   {
6572     for (i = 0; i < NUM_CUSTOM_ELEMENTS; i++)
6573     {
6574       int element = EL_CUSTOM_START + i;
6575       struct ElementInfo *ei = &element_info[element];
6576
6577       if (ei->access_direction == MV_NO_DIRECTION)
6578         ei->access_direction = MV_ALL_DIRECTIONS;
6579     }
6580   }
6581
6582   // correct custom element values (fix invalid values for all versions)
6583   if (1)
6584   {
6585     for (i = 0; i < NUM_CUSTOM_ELEMENTS; i++)
6586     {
6587       int element = EL_CUSTOM_START + i;
6588       struct ElementInfo *ei = &element_info[element];
6589
6590       for (j = 0; j < ei->num_change_pages; j++)
6591       {
6592         struct ElementChangeInfo *change = &ei->change_page[j];
6593
6594         if (change->trigger_player == CH_PLAYER_NONE)
6595           change->trigger_player = CH_PLAYER_ANY;
6596
6597         if (change->trigger_side == CH_SIDE_NONE)
6598           change->trigger_side = CH_SIDE_ANY;
6599       }
6600     }
6601   }
6602
6603   // initialize "can_explode" field for old levels which did not store this
6604   // !!! CHECK THIS -- "<= 3,1,0,0" IS PROBABLY WRONG !!!
6605   if (level->game_version <= VERSION_IDENT(3,1,0,0))
6606   {
6607     for (i = 0; i < NUM_CUSTOM_ELEMENTS; i++)
6608     {
6609       int element = EL_CUSTOM_START + i;
6610
6611       if (EXPLODES_1X1_OLD(element))
6612         element_info[element].explosion_type = EXPLODES_1X1;
6613
6614       SET_PROPERTY(element, EP_CAN_EXPLODE, (EXPLODES_BY_FIRE(element) ||
6615                                              EXPLODES_SMASHED(element) ||
6616                                              EXPLODES_IMPACT(element)));
6617     }
6618   }
6619
6620   // correct previously hard-coded move delay values for maze runner style
6621   if (level->game_version < VERSION_IDENT(3,1,1,0))
6622   {
6623     for (i = 0; i < NUM_CUSTOM_ELEMENTS; i++)
6624     {
6625       int element = EL_CUSTOM_START + i;
6626
6627       if (element_info[element].move_pattern & MV_MAZE_RUNNER_STYLE)
6628       {
6629         // previously hard-coded and therefore ignored
6630         element_info[element].move_delay_fixed = 9;
6631         element_info[element].move_delay_random = 0;
6632       }
6633     }
6634   }
6635
6636   // set some other uninitialized values of custom elements in older levels
6637   if (level->game_version < VERSION_IDENT(3,1,0,0))
6638   {
6639     for (i = 0; i < NUM_CUSTOM_ELEMENTS; i++)
6640     {
6641       int element = EL_CUSTOM_START + i;
6642
6643       element_info[element].access_direction = MV_ALL_DIRECTIONS;
6644
6645       element_info[element].explosion_delay = 17;
6646       element_info[element].ignition_delay = 8;
6647     }
6648   }
6649
6650   // set mouse click change events to work for left/middle/right mouse button
6651   if (level->game_version < VERSION_IDENT(4,2,3,0))
6652   {
6653     for (i = 0; i < NUM_CUSTOM_ELEMENTS; i++)
6654     {
6655       int element = EL_CUSTOM_START + i;
6656       struct ElementInfo *ei = &element_info[element];
6657
6658       for (j = 0; j < ei->num_change_pages; j++)
6659       {
6660         struct ElementChangeInfo *change = &ei->change_page[j];
6661
6662         if (change->has_event[CE_CLICKED_BY_MOUSE] ||
6663             change->has_event[CE_PRESSED_BY_MOUSE] ||
6664             change->has_event[CE_MOUSE_CLICKED_ON_X] ||
6665             change->has_event[CE_MOUSE_PRESSED_ON_X])
6666           change->trigger_side = CH_SIDE_ANY;
6667       }
6668     }
6669   }
6670 }
6671
6672 static void LoadLevel_InitElements(struct LevelInfo *level)
6673 {
6674   LoadLevel_InitStandardElements(level);
6675
6676   if (level->file_has_custom_elements)
6677     LoadLevel_InitCustomElements(level);
6678
6679   // initialize element properties for level editor etc.
6680   InitElementPropertiesEngine(level->game_version);
6681   InitElementPropertiesGfxElement();
6682 }
6683
6684 static void LoadLevel_InitPlayfield(struct LevelInfo *level)
6685 {
6686   int x, y;
6687
6688   // map elements that have changed in newer versions
6689   for (y = 0; y < level->fieldy; y++)
6690     for (x = 0; x < level->fieldx; x++)
6691       level->field[x][y] = getMappedElementByVersion(level->field[x][y],
6692                                                      level->game_version);
6693
6694   // clear unused playfield data (nicer if level gets resized in editor)
6695   for (x = 0; x < MAX_LEV_FIELDX; x++)
6696     for (y = 0; y < MAX_LEV_FIELDY; y++)
6697       if (x >= level->fieldx || y >= level->fieldy)
6698         level->field[x][y] = EL_EMPTY;
6699
6700   // copy elements to runtime playfield array
6701   for (x = 0; x < MAX_LEV_FIELDX; x++)
6702     for (y = 0; y < MAX_LEV_FIELDY; y++)
6703       Tile[x][y] = level->field[x][y];
6704
6705   // initialize level size variables for faster access
6706   lev_fieldx = level->fieldx;
6707   lev_fieldy = level->fieldy;
6708
6709   // determine border element for this level
6710   if (level->file_info.type == LEVEL_FILE_TYPE_DC)
6711     BorderElement = EL_EMPTY;   // (in editor, SetBorderElement() is used)
6712   else
6713     SetBorderElement();
6714 }
6715
6716 static void LoadLevel_InitNativeEngines(struct LevelInfo *level)
6717 {
6718   struct LevelFileInfo *level_file_info = &level->file_info;
6719
6720   if (level_file_info->type == LEVEL_FILE_TYPE_RND)
6721     CopyNativeLevel_RND_to_Native(level);
6722 }
6723
6724 static void LoadLevelTemplate_LoadAndInit(void)
6725 {
6726   LoadLevelFromFileInfo(&level_template, &level_template.file_info, FALSE);
6727
6728   LoadLevel_InitVersion(&level_template);
6729   LoadLevel_InitElements(&level_template);
6730   LoadLevel_InitSettings(&level_template);
6731
6732   ActivateLevelTemplate();
6733 }
6734
6735 void LoadLevelTemplate(int nr)
6736 {
6737   if (!fileExists(getGlobalLevelTemplateFilename()))
6738   {
6739     Warn("no level template found for this level");
6740
6741     return;
6742   }
6743
6744   setLevelFileInfo(&level_template.file_info, nr);
6745
6746   LoadLevelTemplate_LoadAndInit();
6747 }
6748
6749 static void LoadNetworkLevelTemplate(struct NetworkLevelInfo *network_level)
6750 {
6751   copyLevelFileInfo(&network_level->tmpl_info, &level_template.file_info);
6752
6753   LoadLevelTemplate_LoadAndInit();
6754 }
6755
6756 static void LoadLevel_LoadAndInit(struct NetworkLevelInfo *network_level)
6757 {
6758   LoadLevelFromFileInfo(&level, &level.file_info, FALSE);
6759
6760   if (level.use_custom_template)
6761   {
6762     if (network_level != NULL)
6763       LoadNetworkLevelTemplate(network_level);
6764     else
6765       LoadLevelTemplate(-1);
6766   }
6767
6768   LoadLevel_InitVersion(&level);
6769   LoadLevel_InitElements(&level);
6770   LoadLevel_InitPlayfield(&level);
6771   LoadLevel_InitSettings(&level);
6772
6773   LoadLevel_InitNativeEngines(&level);
6774 }
6775
6776 void LoadLevel(int nr)
6777 {
6778   SetLevelSetInfo(leveldir_current->identifier, nr);
6779
6780   setLevelFileInfo(&level.file_info, nr);
6781
6782   LoadLevel_LoadAndInit(NULL);
6783 }
6784
6785 void LoadLevelInfoOnly(int nr)
6786 {
6787   setLevelFileInfo(&level.file_info, nr);
6788
6789   LoadLevelFromFileInfo(&level, &level.file_info, TRUE);
6790 }
6791
6792 void LoadNetworkLevel(struct NetworkLevelInfo *network_level)
6793 {
6794   SetLevelSetInfo(network_level->leveldir_identifier,
6795                   network_level->file_info.nr);
6796
6797   copyLevelFileInfo(&network_level->file_info, &level.file_info);
6798
6799   LoadLevel_LoadAndInit(network_level);
6800 }
6801
6802 static int SaveLevel_VERS(FILE *file, struct LevelInfo *level)
6803 {
6804   int chunk_size = 0;
6805
6806   chunk_size += putFileVersion(file, level->file_version);
6807   chunk_size += putFileVersion(file, level->game_version);
6808
6809   return chunk_size;
6810 }
6811
6812 static int SaveLevel_DATE(FILE *file, struct LevelInfo *level)
6813 {
6814   int chunk_size = 0;
6815
6816   chunk_size += putFile16BitBE(file, level->creation_date.year);
6817   chunk_size += putFile8Bit(file,    level->creation_date.month);
6818   chunk_size += putFile8Bit(file,    level->creation_date.day);
6819
6820   return chunk_size;
6821 }
6822
6823 #if ENABLE_HISTORIC_CHUNKS
6824 static void SaveLevel_HEAD(FILE *file, struct LevelInfo *level)
6825 {
6826   int i, x, y;
6827
6828   putFile8Bit(file, level->fieldx);
6829   putFile8Bit(file, level->fieldy);
6830
6831   putFile16BitBE(file, level->time);
6832   putFile16BitBE(file, level->gems_needed);
6833
6834   for (i = 0; i < MAX_LEVEL_NAME_LEN; i++)
6835     putFile8Bit(file, level->name[i]);
6836
6837   for (i = 0; i < LEVEL_SCORE_ELEMENTS; i++)
6838     putFile8Bit(file, level->score[i]);
6839
6840   for (i = 0; i < STD_ELEMENT_CONTENTS; i++)
6841     for (y = 0; y < 3; y++)
6842       for (x = 0; x < 3; x++)
6843         putFile8Bit(file, (level->encoding_16bit_yamyam ? EL_EMPTY :
6844                            level->yamyam_content[i].e[x][y]));
6845   putFile8Bit(file, level->amoeba_speed);
6846   putFile8Bit(file, level->time_magic_wall);
6847   putFile8Bit(file, level->time_wheel);
6848   putFile8Bit(file, (level->encoding_16bit_amoeba ? EL_EMPTY :
6849                      level->amoeba_content));
6850   putFile8Bit(file, (level->initial_player_stepsize == STEPSIZE_FAST ? 1 : 0));
6851   putFile8Bit(file, (level->initial_gravity ? 1 : 0));
6852   putFile8Bit(file, (level->encoding_16bit_field ? 1 : 0));
6853   putFile8Bit(file, (level->em_slippery_gems ? 1 : 0));
6854
6855   putFile8Bit(file, (level->use_custom_template ? 1 : 0));
6856
6857   putFile8Bit(file, (level->block_last_field ? 1 : 0));
6858   putFile8Bit(file, (level->sp_block_last_field ? 1 : 0));
6859   putFile32BitBE(file, level->can_move_into_acid_bits);
6860   putFile8Bit(file, level->dont_collide_with_bits);
6861
6862   putFile8Bit(file, (level->use_spring_bug ? 1 : 0));
6863   putFile8Bit(file, (level->use_step_counter ? 1 : 0));
6864
6865   putFile8Bit(file, (level->instant_relocation ? 1 : 0));
6866   putFile8Bit(file, (level->can_pass_to_walkable ? 1 : 0));
6867   putFile8Bit(file, (level->grow_into_diggable ? 1 : 0));
6868
6869   putFile8Bit(file, level->game_engine_type);
6870
6871   WriteUnusedBytesToFile(file, LEVEL_CHUNK_HEAD_UNUSED);
6872 }
6873 #endif
6874
6875 static int SaveLevel_NAME(FILE *file, struct LevelInfo *level)
6876 {
6877   int chunk_size = 0;
6878   int i;
6879
6880   for (i = 0; i < MAX_LEVEL_NAME_LEN; i++)
6881     chunk_size += putFile8Bit(file, level->name[i]);
6882
6883   return chunk_size;
6884 }
6885
6886 static int SaveLevel_AUTH(FILE *file, struct LevelInfo *level)
6887 {
6888   int chunk_size = 0;
6889   int i;
6890
6891   for (i = 0; i < MAX_LEVEL_AUTHOR_LEN; i++)
6892     chunk_size += putFile8Bit(file, level->author[i]);
6893
6894   return chunk_size;
6895 }
6896
6897 #if ENABLE_HISTORIC_CHUNKS
6898 static int SaveLevel_BODY(FILE *file, struct LevelInfo *level)
6899 {
6900   int chunk_size = 0;
6901   int x, y;
6902
6903   for (y = 0; y < level->fieldy; y++)
6904     for (x = 0; x < level->fieldx; x++)
6905       if (level->encoding_16bit_field)
6906         chunk_size += putFile16BitBE(file, level->field[x][y]);
6907       else
6908         chunk_size += putFile8Bit(file, level->field[x][y]);
6909
6910   return chunk_size;
6911 }
6912 #endif
6913
6914 static int SaveLevel_BODY(FILE *file, struct LevelInfo *level)
6915 {
6916   int chunk_size = 0;
6917   int x, y;
6918
6919   for (y = 0; y < level->fieldy; y++) 
6920     for (x = 0; x < level->fieldx; x++) 
6921       chunk_size += putFile16BitBE(file, level->field[x][y]);
6922
6923   return chunk_size;
6924 }
6925
6926 #if ENABLE_HISTORIC_CHUNKS
6927 static void SaveLevel_CONT(FILE *file, struct LevelInfo *level)
6928 {
6929   int i, x, y;
6930
6931   putFile8Bit(file, EL_YAMYAM);
6932   putFile8Bit(file, level->num_yamyam_contents);
6933   putFile8Bit(file, 0);
6934   putFile8Bit(file, 0);
6935
6936   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
6937     for (y = 0; y < 3; y++)
6938       for (x = 0; x < 3; x++)
6939         if (level->encoding_16bit_field)
6940           putFile16BitBE(file, level->yamyam_content[i].e[x][y]);
6941         else
6942           putFile8Bit(file, level->yamyam_content[i].e[x][y]);
6943 }
6944 #endif
6945
6946 #if ENABLE_HISTORIC_CHUNKS
6947 static void SaveLevel_CNT2(FILE *file, struct LevelInfo *level, int element)
6948 {
6949   int i, x, y;
6950   int num_contents, content_xsize, content_ysize;
6951   int content_array[MAX_ELEMENT_CONTENTS][3][3];
6952
6953   if (element == EL_YAMYAM)
6954   {
6955     num_contents = level->num_yamyam_contents;
6956     content_xsize = 3;
6957     content_ysize = 3;
6958
6959     for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
6960       for (y = 0; y < 3; y++)
6961         for (x = 0; x < 3; x++)
6962           content_array[i][x][y] = level->yamyam_content[i].e[x][y];
6963   }
6964   else if (element == EL_BD_AMOEBA)
6965   {
6966     num_contents = 1;
6967     content_xsize = 1;
6968     content_ysize = 1;
6969
6970     for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
6971       for (y = 0; y < 3; y++)
6972         for (x = 0; x < 3; x++)
6973           content_array[i][x][y] = EL_EMPTY;
6974     content_array[0][0][0] = level->amoeba_content;
6975   }
6976   else
6977   {
6978     // chunk header already written -- write empty chunk data
6979     WriteUnusedBytesToFile(file, LEVEL_CHUNK_CNT2_SIZE);
6980
6981     Warn("cannot save content for element '%d'", element);
6982
6983     return;
6984   }
6985
6986   putFile16BitBE(file, element);
6987   putFile8Bit(file, num_contents);
6988   putFile8Bit(file, content_xsize);
6989   putFile8Bit(file, content_ysize);
6990
6991   WriteUnusedBytesToFile(file, LEVEL_CHUNK_CNT2_UNUSED);
6992
6993   for (i = 0; i < MAX_ELEMENT_CONTENTS; i++)
6994     for (y = 0; y < 3; y++)
6995       for (x = 0; x < 3; x++)
6996         putFile16BitBE(file, content_array[i][x][y]);
6997 }
6998 #endif
6999
7000 #if ENABLE_HISTORIC_CHUNKS
7001 static int SaveLevel_CNT3(FILE *file, struct LevelInfo *level, int element)
7002 {
7003   int envelope_nr = element - EL_ENVELOPE_1;
7004   int envelope_len = strlen(level->envelope_text[envelope_nr]) + 1;
7005   int chunk_size = 0;
7006   int i;
7007
7008   chunk_size += putFile16BitBE(file, element);
7009   chunk_size += putFile16BitBE(file, envelope_len);
7010   chunk_size += putFile8Bit(file, level->envelope_xsize[envelope_nr]);
7011   chunk_size += putFile8Bit(file, level->envelope_ysize[envelope_nr]);
7012
7013   WriteUnusedBytesToFile(file, LEVEL_CHUNK_CNT3_UNUSED);
7014   chunk_size += LEVEL_CHUNK_CNT3_UNUSED;
7015
7016   for (i = 0; i < envelope_len; i++)
7017     chunk_size += putFile8Bit(file, level->envelope_text[envelope_nr][i]);
7018
7019   return chunk_size;
7020 }
7021 #endif
7022
7023 #if ENABLE_HISTORIC_CHUNKS
7024 static void SaveLevel_CUS1(FILE *file, struct LevelInfo *level,
7025                            int num_changed_custom_elements)
7026 {
7027   int i, check = 0;
7028
7029   putFile16BitBE(file, num_changed_custom_elements);
7030
7031   for (i = 0; i < NUM_CUSTOM_ELEMENTS; i++)
7032   {
7033     int element = EL_CUSTOM_START + i;
7034
7035     struct ElementInfo *ei = &element_info[element];
7036
7037     if (ei->properties[EP_BITFIELD_BASE_NR] != EP_BITMASK_DEFAULT)
7038     {
7039       if (check < num_changed_custom_elements)
7040       {
7041         putFile16BitBE(file, element);
7042         putFile32BitBE(file, ei->properties[EP_BITFIELD_BASE_NR]);
7043       }
7044
7045       check++;
7046     }
7047   }
7048
7049   if (check != num_changed_custom_elements)     // should not happen
7050     Warn("inconsistent number of custom element properties");
7051 }
7052 #endif
7053
7054 #if ENABLE_HISTORIC_CHUNKS
7055 static void SaveLevel_CUS2(FILE *file, struct LevelInfo *level,
7056                            int num_changed_custom_elements)
7057 {
7058   int i, check = 0;
7059
7060   putFile16BitBE(file, num_changed_custom_elements);
7061
7062   for (i = 0; i < NUM_CUSTOM_ELEMENTS; i++)
7063   {
7064     int element = EL_CUSTOM_START + i;
7065
7066     if (element_info[element].change->target_element != EL_EMPTY_SPACE)
7067     {
7068       if (check < num_changed_custom_elements)
7069       {
7070         putFile16BitBE(file, element);
7071         putFile16BitBE(file, element_info[element].change->target_element);
7072       }
7073
7074       check++;
7075     }
7076   }
7077
7078   if (check != num_changed_custom_elements)     // should not happen
7079     Warn("inconsistent number of custom target elements");
7080 }
7081 #endif
7082
7083 #if ENABLE_HISTORIC_CHUNKS
7084 static void SaveLevel_CUS3(FILE *file, struct LevelInfo *level,
7085                            int num_changed_custom_elements)
7086 {
7087   int i, j, x, y, check = 0;
7088
7089   putFile16BitBE(file, num_changed_custom_elements);
7090
7091   for (i = 0; i < NUM_CUSTOM_ELEMENTS; i++)
7092   {
7093     int element = EL_CUSTOM_START + i;
7094     struct ElementInfo *ei = &element_info[element];
7095
7096     if (ei->modified_settings)
7097     {
7098       if (check < num_changed_custom_elements)
7099       {
7100         putFile16BitBE(file, element);
7101
7102         for (j = 0; j < MAX_ELEMENT_NAME_LEN; j++)
7103           putFile8Bit(file, ei->description[j]);
7104
7105         putFile32BitBE(file, ei->properties[EP_BITFIELD_BASE_NR]);
7106
7107         // some free bytes for future properties and padding
7108         WriteUnusedBytesToFile(file, 7);
7109
7110         putFile8Bit(file, ei->use_gfx_element);
7111         putFile16BitBE(file, ei->gfx_element_initial);
7112
7113         putFile8Bit(file, ei->collect_score_initial);
7114         putFile8Bit(file, ei->collect_count_initial);
7115
7116         putFile16BitBE(file, ei->push_delay_fixed);
7117         putFile16BitBE(file, ei->push_delay_random);
7118         putFile16BitBE(file, ei->move_delay_fixed);
7119         putFile16BitBE(file, ei->move_delay_random);
7120
7121         putFile16BitBE(file, ei->move_pattern);
7122         putFile8Bit(file, ei->move_direction_initial);
7123         putFile8Bit(file, ei->move_stepsize);
7124
7125         for (y = 0; y < 3; y++)
7126           for (x = 0; x < 3; x++)
7127             putFile16BitBE(file, ei->content.e[x][y]);
7128
7129         putFile32BitBE(file, ei->change->events);
7130
7131         putFile16BitBE(file, ei->change->target_element);
7132
7133         putFile16BitBE(file, ei->change->delay_fixed);
7134         putFile16BitBE(file, ei->change->delay_random);
7135         putFile16BitBE(file, ei->change->delay_frames);
7136
7137         putFile16BitBE(file, ei->change->initial_trigger_element);
7138
7139         putFile8Bit(file, ei->change->explode);
7140         putFile8Bit(file, ei->change->use_target_content);
7141         putFile8Bit(file, ei->change->only_if_complete);
7142         putFile8Bit(file, ei->change->use_random_replace);
7143
7144         putFile8Bit(file, ei->change->random_percentage);
7145         putFile8Bit(file, ei->change->replace_when);
7146
7147         for (y = 0; y < 3; y++)
7148           for (x = 0; x < 3; x++)
7149             putFile16BitBE(file, ei->change->content.e[x][y]);
7150
7151         putFile8Bit(file, ei->slippery_type);
7152
7153         // some free bytes for future properties and padding
7154         WriteUnusedBytesToFile(file, LEVEL_CPART_CUS3_UNUSED);
7155       }
7156
7157       check++;
7158     }
7159   }
7160
7161   if (check != num_changed_custom_elements)     // should not happen
7162     Warn("inconsistent number of custom element properties");
7163 }
7164 #endif
7165
7166 #if ENABLE_HISTORIC_CHUNKS
7167 static void SaveLevel_CUS4(FILE *file, struct LevelInfo *level, int element)
7168 {
7169   struct ElementInfo *ei = &element_info[element];
7170   int i, j, x, y;
7171
7172   // ---------- custom element base property values (96 bytes) ----------------
7173
7174   putFile16BitBE(file, element);
7175
7176   for (i = 0; i < MAX_ELEMENT_NAME_LEN; i++)
7177     putFile8Bit(file, ei->description[i]);
7178
7179   putFile32BitBE(file, ei->properties[EP_BITFIELD_BASE_NR]);
7180
7181   WriteUnusedBytesToFile(file, 4);      // reserved for more base properties
7182
7183   putFile8Bit(file, ei->num_change_pages);
7184
7185   putFile16BitBE(file, ei->ce_value_fixed_initial);
7186   putFile16BitBE(file, ei->ce_value_random_initial);
7187   putFile8Bit(file, ei->use_last_ce_value);
7188
7189   putFile8Bit(file, ei->use_gfx_element);
7190   putFile16BitBE(file, ei->gfx_element_initial);
7191
7192   putFile8Bit(file, ei->collect_score_initial);
7193   putFile8Bit(file, ei->collect_count_initial);
7194
7195   putFile8Bit(file, ei->drop_delay_fixed);
7196   putFile8Bit(file, ei->push_delay_fixed);
7197   putFile8Bit(file, ei->drop_delay_random);
7198   putFile8Bit(file, ei->push_delay_random);
7199   putFile16BitBE(file, ei->move_delay_fixed);
7200   putFile16BitBE(file, ei->move_delay_random);
7201
7202   // bits 0 - 15 of "move_pattern" ...
7203   putFile16BitBE(file, ei->move_pattern & 0xffff);
7204   putFile8Bit(file, ei->move_direction_initial);
7205   putFile8Bit(file, ei->move_stepsize);
7206
7207   putFile8Bit(file, ei->slippery_type);
7208
7209   for (y = 0; y < 3; y++)
7210     for (x = 0; x < 3; x++)
7211       putFile16BitBE(file, ei->content.e[x][y]);
7212
7213   putFile16BitBE(file, ei->move_enter_element);
7214   putFile16BitBE(file, ei->move_leave_element);
7215   putFile8Bit(file, ei->move_leave_type);
7216
7217   // ... bits 16 - 31 of "move_pattern" (not nice, but downward compatible)
7218   putFile16BitBE(file, (ei->move_pattern >> 16) & 0xffff);
7219
7220   putFile8Bit(file, ei->access_direction);
7221
7222   putFile8Bit(file, ei->explosion_delay);
7223   putFile8Bit(file, ei->ignition_delay);
7224   putFile8Bit(file, ei->explosion_type);
7225
7226   // some free bytes for future custom property values and padding
7227   WriteUnusedBytesToFile(file, 1);
7228
7229   // ---------- change page property values (48 bytes) ------------------------
7230
7231   for (i = 0; i < ei->num_change_pages; i++)
7232   {
7233     struct ElementChangeInfo *change = &ei->change_page[i];
7234     unsigned int event_bits;
7235
7236     // bits 0 - 31 of "has_event[]" ...
7237     event_bits = 0;
7238     for (j = 0; j < MIN(NUM_CHANGE_EVENTS, 32); j++)
7239       if (change->has_event[j])
7240         event_bits |= (1 << j);
7241     putFile32BitBE(file, event_bits);
7242
7243     putFile16BitBE(file, change->target_element);
7244
7245     putFile16BitBE(file, change->delay_fixed);
7246     putFile16BitBE(file, change->delay_random);
7247     putFile16BitBE(file, change->delay_frames);
7248
7249     putFile16BitBE(file, change->initial_trigger_element);
7250
7251     putFile8Bit(file, change->explode);
7252     putFile8Bit(file, change->use_target_content);
7253     putFile8Bit(file, change->only_if_complete);
7254     putFile8Bit(file, change->use_random_replace);
7255
7256     putFile8Bit(file, change->random_percentage);
7257     putFile8Bit(file, change->replace_when);
7258
7259     for (y = 0; y < 3; y++)
7260       for (x = 0; x < 3; x++)
7261         putFile16BitBE(file, change->target_content.e[x][y]);
7262
7263     putFile8Bit(file, change->can_change);
7264
7265     putFile8Bit(file, change->trigger_side);
7266
7267     putFile8Bit(file, change->trigger_player);
7268     putFile8Bit(file, (change->trigger_page == CH_PAGE_ANY ? CH_PAGE_ANY_FILE :
7269                        log_2(change->trigger_page)));
7270
7271     putFile8Bit(file, change->has_action);
7272     putFile8Bit(file, change->action_type);
7273     putFile8Bit(file, change->action_mode);
7274     putFile16BitBE(file, change->action_arg);
7275
7276     // ... bits 32 - 39 of "has_event[]" (not nice, but downward compatible)
7277     event_bits = 0;
7278     for (j = 32; j < NUM_CHANGE_EVENTS; j++)
7279       if (change->has_event[j])
7280         event_bits |= (1 << (j - 32));
7281     putFile8Bit(file, event_bits);
7282   }
7283 }
7284 #endif
7285
7286 #if ENABLE_HISTORIC_CHUNKS
7287 static void SaveLevel_GRP1(FILE *file, struct LevelInfo *level, int element)
7288 {
7289   struct ElementInfo *ei = &element_info[element];
7290   struct ElementGroupInfo *group = ei->group;
7291   int i;
7292
7293   putFile16BitBE(file, element);
7294
7295   for (i = 0; i < MAX_ELEMENT_NAME_LEN; i++)
7296     putFile8Bit(file, ei->description[i]);
7297
7298   putFile8Bit(file, group->num_elements);
7299
7300   putFile8Bit(file, ei->use_gfx_element);
7301   putFile16BitBE(file, ei->gfx_element_initial);
7302
7303   putFile8Bit(file, group->choice_mode);
7304
7305   // some free bytes for future values and padding
7306   WriteUnusedBytesToFile(file, 3);
7307
7308   for (i = 0; i < MAX_ELEMENTS_IN_GROUP; i++)
7309     putFile16BitBE(file, group->element[i]);
7310 }
7311 #endif
7312
7313 static int SaveLevel_MicroChunk(FILE *file, struct LevelFileConfigInfo *entry,
7314                                 boolean write_element)
7315 {
7316   int save_type = entry->save_type;
7317   int data_type = entry->data_type;
7318   int conf_type = entry->conf_type;
7319   int byte_mask = conf_type & CONF_MASK_BYTES;
7320   int element = entry->element;
7321   int default_value = entry->default_value;
7322   int num_bytes = 0;
7323   boolean modified = FALSE;
7324
7325   if (byte_mask != CONF_MASK_MULTI_BYTES)
7326   {
7327     void *value_ptr = entry->value;
7328     int value = (data_type == TYPE_BOOLEAN ? *(boolean *)value_ptr :
7329                  *(int *)value_ptr);
7330
7331     // check if any settings have been modified before saving them
7332     if (value != default_value)
7333       modified = TRUE;
7334
7335     // do not save if explicitly told or if unmodified default settings
7336     if ((save_type == SAVE_CONF_NEVER) ||
7337         (save_type == SAVE_CONF_WHEN_CHANGED && !modified))
7338       return 0;
7339
7340     if (write_element)
7341       num_bytes += putFile16BitBE(file, element);
7342
7343     num_bytes += putFile8Bit(file, conf_type);
7344     num_bytes += (byte_mask == CONF_MASK_1_BYTE ? putFile8Bit   (file, value) :
7345                   byte_mask == CONF_MASK_2_BYTE ? putFile16BitBE(file, value) :
7346                   byte_mask == CONF_MASK_4_BYTE ? putFile32BitBE(file, value) :
7347                   0);
7348   }
7349   else if (data_type == TYPE_STRING)
7350   {
7351     char *default_string = entry->default_string;
7352     char *string = (char *)(entry->value);
7353     int string_length = strlen(string);
7354     int i;
7355
7356     // check if any settings have been modified before saving them
7357     if (!strEqual(string, default_string))
7358       modified = TRUE;
7359
7360     // do not save if explicitly told or if unmodified default settings
7361     if ((save_type == SAVE_CONF_NEVER) ||
7362         (save_type == SAVE_CONF_WHEN_CHANGED && !modified))
7363       return 0;
7364
7365     if (write_element)
7366       num_bytes += putFile16BitBE(file, element);
7367
7368     num_bytes += putFile8Bit(file, conf_type);
7369     num_bytes += putFile16BitBE(file, string_length);
7370
7371     for (i = 0; i < string_length; i++)
7372       num_bytes += putFile8Bit(file, string[i]);
7373   }
7374   else if (data_type == TYPE_ELEMENT_LIST)
7375   {
7376     int *element_array = (int *)(entry->value);
7377     int num_elements = *(int *)(entry->num_entities);
7378     int i;
7379
7380     // check if any settings have been modified before saving them
7381     for (i = 0; i < num_elements; i++)
7382       if (element_array[i] != default_value)
7383         modified = TRUE;
7384
7385     // do not save if explicitly told or if unmodified default settings
7386     if ((save_type == SAVE_CONF_NEVER) ||
7387         (save_type == SAVE_CONF_WHEN_CHANGED && !modified))
7388       return 0;
7389
7390     if (write_element)
7391       num_bytes += putFile16BitBE(file, element);
7392
7393     num_bytes += putFile8Bit(file, conf_type);
7394     num_bytes += putFile16BitBE(file, num_elements * CONF_ELEMENT_NUM_BYTES);
7395
7396     for (i = 0; i < num_elements; i++)
7397       num_bytes += putFile16BitBE(file, element_array[i]);
7398   }
7399   else if (data_type == TYPE_CONTENT_LIST)
7400   {
7401     struct Content *content = (struct Content *)(entry->value);
7402     int num_contents = *(int *)(entry->num_entities);
7403     int i, x, y;
7404
7405     // check if any settings have been modified before saving them
7406     for (i = 0; i < num_contents; i++)
7407       for (y = 0; y < 3; y++)
7408         for (x = 0; x < 3; x++)
7409           if (content[i].e[x][y] != default_value)
7410             modified = TRUE;
7411
7412     // do not save if explicitly told or if unmodified default settings
7413     if ((save_type == SAVE_CONF_NEVER) ||
7414         (save_type == SAVE_CONF_WHEN_CHANGED && !modified))
7415       return 0;
7416
7417     if (write_element)
7418       num_bytes += putFile16BitBE(file, element);
7419
7420     num_bytes += putFile8Bit(file, conf_type);
7421     num_bytes += putFile16BitBE(file, num_contents * CONF_CONTENT_NUM_BYTES);
7422
7423     for (i = 0; i < num_contents; i++)
7424       for (y = 0; y < 3; y++)
7425         for (x = 0; x < 3; x++)
7426           num_bytes += putFile16BitBE(file, content[i].e[x][y]);
7427   }
7428
7429   return num_bytes;
7430 }
7431
7432 static int SaveLevel_INFO(FILE *file, struct LevelInfo *level)
7433 {
7434   int chunk_size = 0;
7435   int i;
7436
7437   li = *level;          // copy level data into temporary buffer
7438
7439   for (i = 0; chunk_config_INFO[i].data_type != -1; i++)
7440     chunk_size += SaveLevel_MicroChunk(file, &chunk_config_INFO[i], FALSE);
7441
7442   return chunk_size;
7443 }
7444
7445 static int SaveLevel_ELEM(FILE *file, struct LevelInfo *level)
7446 {
7447   int chunk_size = 0;
7448   int i;
7449
7450   li = *level;          // copy level data into temporary buffer
7451
7452   for (i = 0; chunk_config_ELEM[i].data_type != -1; i++)
7453     chunk_size += SaveLevel_MicroChunk(file, &chunk_config_ELEM[i], TRUE);
7454
7455   return chunk_size;
7456 }
7457
7458 static int SaveLevel_NOTE(FILE *file, struct LevelInfo *level, int element)
7459 {
7460   int envelope_nr = element - EL_ENVELOPE_1;
7461   int chunk_size = 0;
7462   int i;
7463
7464   chunk_size += putFile16BitBE(file, element);
7465
7466   // copy envelope data into temporary buffer
7467   xx_envelope = level->envelope[envelope_nr];
7468
7469   for (i = 0; chunk_config_NOTE[i].data_type != -1; i++)
7470     chunk_size += SaveLevel_MicroChunk(file, &chunk_config_NOTE[i], FALSE);
7471
7472   return chunk_size;
7473 }
7474
7475 static int SaveLevel_CUSX(FILE *file, struct LevelInfo *level, int element)
7476 {
7477   struct ElementInfo *ei = &element_info[element];
7478   int chunk_size = 0;
7479   int i, j;
7480
7481   chunk_size += putFile16BitBE(file, element);
7482
7483   xx_ei = *ei;          // copy element data into temporary buffer
7484
7485   // set default description string for this specific element
7486   strcpy(xx_default_description, getDefaultElementDescription(ei));
7487
7488   for (i = 0; chunk_config_CUSX_base[i].data_type != -1; i++)
7489     chunk_size += SaveLevel_MicroChunk(file, &chunk_config_CUSX_base[i], FALSE);
7490
7491   for (i = 0; i < ei->num_change_pages; i++)
7492   {
7493     struct ElementChangeInfo *change = &ei->change_page[i];
7494
7495     xx_current_change_page = i;
7496
7497     xx_change = *change;        // copy change data into temporary buffer
7498
7499     resetEventBits();
7500     setEventBitsFromEventFlags(change);
7501
7502     for (j = 0; chunk_config_CUSX_change[j].data_type != -1; j++)
7503       chunk_size += SaveLevel_MicroChunk(file, &chunk_config_CUSX_change[j],
7504                                          FALSE);
7505   }
7506
7507   return chunk_size;
7508 }
7509
7510 static int SaveLevel_GRPX(FILE *file, struct LevelInfo *level, int element)
7511 {
7512   struct ElementInfo *ei = &element_info[element];
7513   struct ElementGroupInfo *group = ei->group;
7514   int chunk_size = 0;
7515   int i;
7516
7517   chunk_size += putFile16BitBE(file, element);
7518
7519   xx_ei = *ei;          // copy element data into temporary buffer
7520   xx_group = *group;    // copy group data into temporary buffer
7521
7522   // set default description string for this specific element
7523   strcpy(xx_default_description, getDefaultElementDescription(ei));
7524
7525   for (i = 0; chunk_config_GRPX[i].data_type != -1; i++)
7526     chunk_size += SaveLevel_MicroChunk(file, &chunk_config_GRPX[i], FALSE);
7527
7528   return chunk_size;
7529 }
7530
7531 static void SaveLevelFromFilename(struct LevelInfo *level, char *filename,
7532                                   boolean save_as_template)
7533 {
7534   int chunk_size;
7535   int i;
7536   FILE *file;
7537
7538   if (!(file = fopen(filename, MODE_WRITE)))
7539   {
7540     Warn("cannot save level file '%s'", filename);
7541
7542     return;
7543   }
7544
7545   level->file_version = FILE_VERSION_ACTUAL;
7546   level->game_version = GAME_VERSION_ACTUAL;
7547
7548   level->creation_date = getCurrentDate();
7549
7550   putFileChunkBE(file, "RND1", CHUNK_SIZE_UNDEFINED);
7551   putFileChunkBE(file, "CAVE", CHUNK_SIZE_NONE);
7552
7553   chunk_size = SaveLevel_VERS(NULL, level);
7554   putFileChunkBE(file, "VERS", chunk_size);
7555   SaveLevel_VERS(file, level);
7556
7557   chunk_size = SaveLevel_DATE(NULL, level);
7558   putFileChunkBE(file, "DATE", chunk_size);
7559   SaveLevel_DATE(file, level);
7560
7561   chunk_size = SaveLevel_NAME(NULL, level);
7562   putFileChunkBE(file, "NAME", chunk_size);
7563   SaveLevel_NAME(file, level);
7564
7565   chunk_size = SaveLevel_AUTH(NULL, level);
7566   putFileChunkBE(file, "AUTH", chunk_size);
7567   SaveLevel_AUTH(file, level);
7568
7569   chunk_size = SaveLevel_INFO(NULL, level);
7570   putFileChunkBE(file, "INFO", chunk_size);
7571   SaveLevel_INFO(file, level);
7572
7573   chunk_size = SaveLevel_BODY(NULL, level);
7574   putFileChunkBE(file, "BODY", chunk_size);
7575   SaveLevel_BODY(file, level);
7576
7577   chunk_size = SaveLevel_ELEM(NULL, level);
7578   if (chunk_size > LEVEL_CHUNK_ELEM_UNCHANGED)          // save if changed
7579   {
7580     putFileChunkBE(file, "ELEM", chunk_size);
7581     SaveLevel_ELEM(file, level);
7582   }
7583
7584   for (i = 0; i < NUM_ENVELOPES; i++)
7585   {
7586     int element = EL_ENVELOPE_1 + i;
7587
7588     chunk_size = SaveLevel_NOTE(NULL, level, element);
7589     if (chunk_size > LEVEL_CHUNK_NOTE_UNCHANGED)        // save if changed
7590     {
7591       putFileChunkBE(file, "NOTE", chunk_size);
7592       SaveLevel_NOTE(file, level, element);
7593     }
7594   }
7595
7596   // if not using template level, check for non-default custom/group elements
7597   if (!level->use_custom_template || save_as_template)
7598   {
7599     for (i = 0; i < NUM_CUSTOM_ELEMENTS; i++)
7600     {
7601       int element = EL_CUSTOM_START + i;
7602
7603       chunk_size = SaveLevel_CUSX(NULL, level, element);
7604       if (chunk_size > LEVEL_CHUNK_CUSX_UNCHANGED)      // save if changed
7605       {
7606         putFileChunkBE(file, "CUSX", chunk_size);
7607         SaveLevel_CUSX(file, level, element);
7608       }
7609     }
7610
7611     for (i = 0; i < NUM_GROUP_ELEMENTS; i++)
7612     {
7613       int element = EL_GROUP_START + i;
7614
7615       chunk_size = SaveLevel_GRPX(NULL, level, element);
7616       if (chunk_size > LEVEL_CHUNK_GRPX_UNCHANGED)      // save if changed
7617       {
7618         putFileChunkBE(file, "GRPX", chunk_size);
7619         SaveLevel_GRPX(file, level, element);
7620       }
7621     }
7622   }
7623
7624   fclose(file);
7625
7626   SetFilePermissions(filename, PERMS_PRIVATE);
7627 }
7628
7629 void SaveLevel(int nr)
7630 {
7631   char *filename = getDefaultLevelFilename(nr);
7632
7633   SaveLevelFromFilename(&level, filename, FALSE);
7634 }
7635
7636 void SaveLevelTemplate(void)
7637 {
7638   char *filename = getLocalLevelTemplateFilename();
7639
7640   SaveLevelFromFilename(&level, filename, TRUE);
7641 }
7642
7643 boolean SaveLevelChecked(int nr)
7644 {
7645   char *filename = getDefaultLevelFilename(nr);
7646   boolean new_level = !fileExists(filename);
7647   boolean level_saved = FALSE;
7648
7649   if (new_level || Request("Save this level and kill the old?", REQ_ASK))
7650   {
7651     SaveLevel(nr);
7652
7653     if (new_level)
7654       Request("Level saved!", REQ_CONFIRM);
7655
7656     level_saved = TRUE;
7657   }
7658
7659   return level_saved;
7660 }
7661
7662 void DumpLevel(struct LevelInfo *level)
7663 {
7664   if (level->no_level_file || level->no_valid_file)
7665   {
7666     Warn("cannot dump -- no valid level file found");
7667
7668     return;
7669   }
7670
7671   PrintLine("-", 79);
7672   Print("Level xxx (file version %08d, game version %08d)\n",
7673         level->file_version, level->game_version);
7674   PrintLine("-", 79);
7675
7676   Print("Level author: '%s'\n", level->author);
7677   Print("Level title:  '%s'\n", level->name);
7678   Print("\n");
7679   Print("Playfield size: %d x %d\n", level->fieldx, level->fieldy);
7680   Print("\n");
7681   Print("Level time:  %d seconds\n", level->time);
7682   Print("Gems needed: %d\n", level->gems_needed);
7683   Print("\n");
7684   Print("Time for magic wall: %d seconds\n", level->time_magic_wall);
7685   Print("Time for wheel:      %d seconds\n", level->time_wheel);
7686   Print("Time for light:      %d seconds\n", level->time_light);
7687   Print("Time for timegate:   %d seconds\n", level->time_timegate);
7688   Print("\n");
7689   Print("Amoeba speed: %d\n", level->amoeba_speed);
7690   Print("\n");
7691
7692   Print("EM style slippery gems:      %s\n", (level->em_slippery_gems ? "yes" : "no"));
7693   Print("Player blocks last field:    %s\n", (level->block_last_field ? "yes" : "no"));
7694   Print("SP player blocks last field: %s\n", (level->sp_block_last_field ? "yes" : "no"));
7695   Print("use spring bug: %s\n", (level->use_spring_bug ? "yes" : "no"));
7696   Print("use step counter: %s\n", (level->use_step_counter ? "yes" : "no"));
7697   Print("rate time over score: %s\n", (level->rate_time_over_score ? "yes" : "no"));
7698
7699   PrintLine("-", 79);
7700 }
7701
7702 void DumpLevels(void)
7703 {
7704   static LevelDirTree *dumplevel_leveldir = NULL;
7705
7706   dumplevel_leveldir = getTreeInfoFromIdentifier(leveldir_first,
7707                                                  global.dumplevel_leveldir);
7708
7709   if (dumplevel_leveldir == NULL)
7710     Fail("no such level identifier: '%s'", global.dumplevel_leveldir);
7711
7712   if (global.dumplevel_level_nr < dumplevel_leveldir->first_level ||
7713       global.dumplevel_level_nr > dumplevel_leveldir->last_level)
7714     Fail("no such level number: %d", global.dumplevel_level_nr);
7715
7716   leveldir_current = dumplevel_leveldir;
7717
7718   LoadLevel(global.dumplevel_level_nr);
7719   DumpLevel(&level);
7720
7721   CloseAllAndExit(0);
7722 }
7723
7724
7725 // ============================================================================
7726 // tape file functions
7727 // ============================================================================
7728
7729 static void setTapeInfoToDefaults(void)
7730 {
7731   int i;
7732
7733   // always start with reliable default values (empty tape)
7734   TapeErase();
7735
7736   // default values (also for pre-1.2 tapes) with only the first player
7737   tape.player_participates[0] = TRUE;
7738   for (i = 1; i < MAX_PLAYERS; i++)
7739     tape.player_participates[i] = FALSE;
7740
7741   // at least one (default: the first) player participates in every tape
7742   tape.num_participating_players = 1;
7743
7744   tape.property_bits = TAPE_PROPERTY_NONE;
7745
7746   tape.level_nr = level_nr;
7747   tape.counter = 0;
7748   tape.changed = FALSE;
7749
7750   tape.recording = FALSE;
7751   tape.playing = FALSE;
7752   tape.pausing = FALSE;
7753
7754   tape.scr_fieldx = SCR_FIELDX_DEFAULT;
7755   tape.scr_fieldy = SCR_FIELDY_DEFAULT;
7756
7757   tape.no_valid_file = FALSE;
7758 }
7759
7760 static int getTapePosSize(struct TapeInfo *tape)
7761 {
7762   int tape_pos_size = 0;
7763
7764   if (tape->use_key_actions)
7765     tape_pos_size += tape->num_participating_players;
7766
7767   if (tape->use_mouse_actions)
7768     tape_pos_size += 3;         // x and y position and mouse button mask
7769
7770   tape_pos_size += 1;           // tape action delay value
7771
7772   return tape_pos_size;
7773 }
7774
7775 static void setTapeActionFlags(struct TapeInfo *tape, int value)
7776 {
7777   tape->use_key_actions = FALSE;
7778   tape->use_mouse_actions = FALSE;
7779
7780   if (value != TAPE_USE_MOUSE_ACTIONS_ONLY)
7781     tape->use_key_actions = TRUE;
7782
7783   if (value != TAPE_USE_KEY_ACTIONS_ONLY)
7784     tape->use_mouse_actions = TRUE;
7785 }
7786
7787 static int getTapeActionValue(struct TapeInfo *tape)
7788 {
7789   return (tape->use_key_actions &&
7790           tape->use_mouse_actions ? TAPE_USE_KEY_AND_MOUSE_ACTIONS :
7791           tape->use_key_actions   ? TAPE_USE_KEY_ACTIONS_ONLY :
7792           tape->use_mouse_actions ? TAPE_USE_MOUSE_ACTIONS_ONLY :
7793           TAPE_ACTIONS_DEFAULT);
7794 }
7795
7796 static int LoadTape_VERS(File *file, int chunk_size, struct TapeInfo *tape)
7797 {
7798   tape->file_version = getFileVersion(file);
7799   tape->game_version = getFileVersion(file);
7800
7801   return chunk_size;
7802 }
7803
7804 static int LoadTape_HEAD(File *file, int chunk_size, struct TapeInfo *tape)
7805 {
7806   int i;
7807
7808   tape->random_seed = getFile32BitBE(file);
7809   tape->date        = getFile32BitBE(file);
7810   tape->length      = getFile32BitBE(file);
7811
7812   // read header fields that are new since version 1.2
7813   if (tape->file_version >= FILE_VERSION_1_2)
7814   {
7815     byte store_participating_players = getFile8Bit(file);
7816     int engine_version;
7817
7818     // since version 1.2, tapes store which players participate in the tape
7819     tape->num_participating_players = 0;
7820     for (i = 0; i < MAX_PLAYERS; i++)
7821     {
7822       tape->player_participates[i] = FALSE;
7823
7824       if (store_participating_players & (1 << i))
7825       {
7826         tape->player_participates[i] = TRUE;
7827         tape->num_participating_players++;
7828       }
7829     }
7830
7831     setTapeActionFlags(tape, getFile8Bit(file));
7832
7833     tape->property_bits = getFile8Bit(file);
7834
7835     ReadUnusedBytesFromFile(file, TAPE_CHUNK_HEAD_UNUSED);
7836
7837     engine_version = getFileVersion(file);
7838     if (engine_version > 0)
7839       tape->engine_version = engine_version;
7840     else
7841       tape->engine_version = tape->game_version;
7842   }
7843
7844   return chunk_size;
7845 }
7846
7847 static int LoadTape_SCRN(File *file, int chunk_size, struct TapeInfo *tape)
7848 {
7849   tape->scr_fieldx = getFile8Bit(file);
7850   tape->scr_fieldy = getFile8Bit(file);
7851
7852   return chunk_size;
7853 }
7854
7855 static int LoadTape_INFO(File *file, int chunk_size, struct TapeInfo *tape)
7856 {
7857   char *level_identifier = NULL;
7858   int level_identifier_size;
7859   int i;
7860
7861   level_identifier_size = getFile16BitBE(file);
7862
7863   level_identifier = checked_malloc(level_identifier_size);
7864
7865   for (i = 0; i < level_identifier_size; i++)
7866     level_identifier[i] = getFile8Bit(file);
7867
7868   strncpy(tape->level_identifier, level_identifier, MAX_FILENAME_LEN);
7869   tape->level_identifier[MAX_FILENAME_LEN] = '\0';
7870
7871   checked_free(level_identifier);
7872
7873   tape->level_nr = getFile16BitBE(file);
7874
7875   chunk_size = 2 + level_identifier_size + 2;
7876
7877   return chunk_size;
7878 }
7879
7880 static int LoadTape_BODY(File *file, int chunk_size, struct TapeInfo *tape)
7881 {
7882   int i, j;
7883   int tape_pos_size = getTapePosSize(tape);
7884   int chunk_size_expected = tape_pos_size * tape->length;
7885
7886   if (chunk_size_expected != chunk_size)
7887   {
7888     ReadUnusedBytesFromFile(file, chunk_size);
7889     return chunk_size_expected;
7890   }
7891
7892   for (i = 0; i < tape->length; i++)
7893   {
7894     if (i >= MAX_TAPE_LEN)
7895     {
7896       Warn("tape truncated -- size exceeds maximum tape size %d",
7897             MAX_TAPE_LEN);
7898
7899       // tape too large; read and ignore remaining tape data from this chunk
7900       for (;i < tape->length; i++)
7901         ReadUnusedBytesFromFile(file, tape_pos_size);
7902
7903       break;
7904     }
7905
7906     if (tape->use_key_actions)
7907     {
7908       for (j = 0; j < MAX_PLAYERS; j++)
7909       {
7910         tape->pos[i].action[j] = MV_NONE;
7911
7912         if (tape->player_participates[j])
7913           tape->pos[i].action[j] = getFile8Bit(file);
7914       }
7915     }
7916
7917     if (tape->use_mouse_actions)
7918     {
7919       tape->pos[i].action[TAPE_ACTION_LX]     = getFile8Bit(file);
7920       tape->pos[i].action[TAPE_ACTION_LY]     = getFile8Bit(file);
7921       tape->pos[i].action[TAPE_ACTION_BUTTON] = getFile8Bit(file);
7922     }
7923
7924     tape->pos[i].delay = getFile8Bit(file);
7925
7926     if (tape->file_version == FILE_VERSION_1_0)
7927     {
7928       // eliminate possible diagonal moves in old tapes
7929       // this is only for backward compatibility
7930
7931       byte joy_dir[4] = { JOY_LEFT, JOY_RIGHT, JOY_UP, JOY_DOWN };
7932       byte action = tape->pos[i].action[0];
7933       int k, num_moves = 0;
7934
7935       for (k = 0; k<4; k++)
7936       {
7937         if (action & joy_dir[k])
7938         {
7939           tape->pos[i + num_moves].action[0] = joy_dir[k];
7940           if (num_moves > 0)
7941             tape->pos[i + num_moves].delay = 0;
7942           num_moves++;
7943         }
7944       }
7945
7946       if (num_moves > 1)
7947       {
7948         num_moves--;
7949         i += num_moves;
7950         tape->length += num_moves;
7951       }
7952     }
7953     else if (tape->file_version < FILE_VERSION_2_0)
7954     {
7955       // convert pre-2.0 tapes to new tape format
7956
7957       if (tape->pos[i].delay > 1)
7958       {
7959         // action part
7960         tape->pos[i + 1] = tape->pos[i];
7961         tape->pos[i + 1].delay = 1;
7962
7963         // delay part
7964         for (j = 0; j < MAX_PLAYERS; j++)
7965           tape->pos[i].action[j] = MV_NONE;
7966         tape->pos[i].delay--;
7967
7968         i++;
7969         tape->length++;
7970       }
7971     }
7972
7973     if (checkEndOfFile(file))
7974       break;
7975   }
7976
7977   if (i != tape->length)
7978     chunk_size = tape_pos_size * i;
7979
7980   return chunk_size;
7981 }
7982
7983 static void LoadTape_SokobanSolution(char *filename)
7984 {
7985   File *file;
7986   int move_delay = TILESIZE / level.initial_player_stepsize[0];
7987
7988   if (!(file = openFile(filename, MODE_READ)))
7989   {
7990     tape.no_valid_file = TRUE;
7991
7992     return;
7993   }
7994
7995   while (!checkEndOfFile(file))
7996   {
7997     unsigned char c = getByteFromFile(file);
7998
7999     if (checkEndOfFile(file))
8000       break;
8001
8002     switch (c)
8003     {
8004       case 'u':
8005       case 'U':
8006         tape.pos[tape.length].action[0] = MV_UP;
8007         tape.pos[tape.length].delay = move_delay + (c < 'a' ? 2 : 0);
8008         tape.length++;
8009         break;
8010
8011       case 'd':
8012       case 'D':
8013         tape.pos[tape.length].action[0] = MV_DOWN;
8014         tape.pos[tape.length].delay = move_delay + (c < 'a' ? 2 : 0);
8015         tape.length++;
8016         break;
8017
8018       case 'l':
8019       case 'L':
8020         tape.pos[tape.length].action[0] = MV_LEFT;
8021         tape.pos[tape.length].delay = move_delay + (c < 'a' ? 2 : 0);
8022         tape.length++;
8023         break;
8024
8025       case 'r':
8026       case 'R':
8027         tape.pos[tape.length].action[0] = MV_RIGHT;
8028         tape.pos[tape.length].delay = move_delay + (c < 'a' ? 2 : 0);
8029         tape.length++;
8030         break;
8031
8032       case '\n':
8033       case '\r':
8034       case '\t':
8035       case ' ':
8036         // ignore white-space characters
8037         break;
8038
8039       default:
8040         tape.no_valid_file = TRUE;
8041
8042         Warn("unsupported Sokoban solution file '%s' ['%d']", filename, c);
8043
8044         break;
8045     }
8046   }
8047
8048   closeFile(file);
8049
8050   if (tape.no_valid_file)
8051     return;
8052
8053   tape.length_frames  = GetTapeLengthFrames();
8054   tape.length_seconds = GetTapeLengthSeconds();
8055 }
8056
8057 void LoadTapeFromFilename(char *filename)
8058 {
8059   char cookie[MAX_LINE_LEN];
8060   char chunk_name[CHUNK_ID_LEN + 1];
8061   File *file;
8062   int chunk_size;
8063
8064   // always start with reliable default values
8065   setTapeInfoToDefaults();
8066
8067   if (strSuffix(filename, ".sln"))
8068   {
8069     LoadTape_SokobanSolution(filename);
8070
8071     return;
8072   }
8073
8074   if (!(file = openFile(filename, MODE_READ)))
8075   {
8076     tape.no_valid_file = TRUE;
8077
8078     return;
8079   }
8080
8081   getFileChunkBE(file, chunk_name, NULL);
8082   if (strEqual(chunk_name, "RND1"))
8083   {
8084     getFile32BitBE(file);               // not used
8085
8086     getFileChunkBE(file, chunk_name, NULL);
8087     if (!strEqual(chunk_name, "TAPE"))
8088     {
8089       tape.no_valid_file = TRUE;
8090
8091       Warn("unknown format of tape file '%s'", filename);
8092
8093       closeFile(file);
8094
8095       return;
8096     }
8097   }
8098   else  // check for pre-2.0 file format with cookie string
8099   {
8100     strcpy(cookie, chunk_name);
8101     if (getStringFromFile(file, &cookie[4], MAX_LINE_LEN - 4) == NULL)
8102       cookie[4] = '\0';
8103     if (strlen(cookie) > 0 && cookie[strlen(cookie) - 1] == '\n')
8104       cookie[strlen(cookie) - 1] = '\0';
8105
8106     if (!checkCookieString(cookie, TAPE_COOKIE_TMPL))
8107     {
8108       tape.no_valid_file = TRUE;
8109
8110       Warn("unknown format of tape file '%s'", filename);
8111
8112       closeFile(file);
8113
8114       return;
8115     }
8116
8117     if ((tape.file_version = getFileVersionFromCookieString(cookie)) == -1)
8118     {
8119       tape.no_valid_file = TRUE;
8120
8121       Warn("unsupported version of tape file '%s'", filename);
8122
8123       closeFile(file);
8124
8125       return;
8126     }
8127
8128     // pre-2.0 tape files have no game version, so use file version here
8129     tape.game_version = tape.file_version;
8130   }
8131
8132   if (tape.file_version < FILE_VERSION_1_2)
8133   {
8134     // tape files from versions before 1.2.0 without chunk structure
8135     LoadTape_HEAD(file, TAPE_CHUNK_HEAD_SIZE, &tape);
8136     LoadTape_BODY(file, 2 * tape.length,      &tape);
8137   }
8138   else
8139   {
8140     static struct
8141     {
8142       char *name;
8143       int size;
8144       int (*loader)(File *, int, struct TapeInfo *);
8145     }
8146     chunk_info[] =
8147     {
8148       { "VERS", TAPE_CHUNK_VERS_SIZE,   LoadTape_VERS },
8149       { "HEAD", TAPE_CHUNK_HEAD_SIZE,   LoadTape_HEAD },
8150       { "SCRN", TAPE_CHUNK_SCRN_SIZE,   LoadTape_SCRN },
8151       { "INFO", -1,                     LoadTape_INFO },
8152       { "BODY", -1,                     LoadTape_BODY },
8153       {  NULL,  0,                      NULL }
8154     };
8155
8156     while (getFileChunkBE(file, chunk_name, &chunk_size))
8157     {
8158       int i = 0;
8159
8160       while (chunk_info[i].name != NULL &&
8161              !strEqual(chunk_name, chunk_info[i].name))
8162         i++;
8163
8164       if (chunk_info[i].name == NULL)
8165       {
8166         Warn("unknown chunk '%s' in tape file '%s'",
8167               chunk_name, filename);
8168
8169         ReadUnusedBytesFromFile(file, chunk_size);
8170       }
8171       else if (chunk_info[i].size != -1 &&
8172                chunk_info[i].size != chunk_size)
8173       {
8174         Warn("wrong size (%d) of chunk '%s' in tape file '%s'",
8175               chunk_size, chunk_name, filename);
8176
8177         ReadUnusedBytesFromFile(file, chunk_size);
8178       }
8179       else
8180       {
8181         // call function to load this tape chunk
8182         int chunk_size_expected =
8183           (chunk_info[i].loader)(file, chunk_size, &tape);
8184
8185         // the size of some chunks cannot be checked before reading other
8186         // chunks first (like "HEAD" and "BODY") that contain some header
8187         // information, so check them here
8188         if (chunk_size_expected != chunk_size)
8189         {
8190           Warn("wrong size (%d) of chunk '%s' in tape file '%s'",
8191                 chunk_size, chunk_name, filename);
8192         }
8193       }
8194     }
8195   }
8196
8197   closeFile(file);
8198
8199   tape.length_frames  = GetTapeLengthFrames();
8200   tape.length_seconds = GetTapeLengthSeconds();
8201
8202 #if 0
8203   Debug("files:LoadTapeFromFilename", "tape file version: %d",
8204         tape.file_version);
8205   Debug("files:LoadTapeFromFilename", "tape game version: %d",
8206         tape.game_version);
8207   Debug("files:LoadTapeFromFilename", "tape engine version: %d",
8208         tape.engine_version);
8209 #endif
8210 }
8211
8212 void LoadTape(int nr)
8213 {
8214   char *filename = getTapeFilename(nr);
8215
8216   LoadTapeFromFilename(filename);
8217 }
8218
8219 void LoadSolutionTape(int nr)
8220 {
8221   char *filename = getSolutionTapeFilename(nr);
8222
8223   LoadTapeFromFilename(filename);
8224
8225   if (TAPE_IS_EMPTY(tape) &&
8226       level.game_engine_type == GAME_ENGINE_TYPE_SP &&
8227       level.native_sp_level->demo.is_available)
8228     CopyNativeTape_SP_to_RND(&level);
8229 }
8230
8231 static boolean checkSaveTape_SCRN(struct TapeInfo *tape)
8232 {
8233   // chunk required for team mode tapes with non-default screen size
8234   return (tape->num_participating_players > 1 &&
8235           (tape->scr_fieldx != SCR_FIELDX_DEFAULT ||
8236            tape->scr_fieldy != SCR_FIELDY_DEFAULT));
8237 }
8238
8239 static void SaveTape_VERS(FILE *file, struct TapeInfo *tape)
8240 {
8241   putFileVersion(file, tape->file_version);
8242   putFileVersion(file, tape->game_version);
8243 }
8244
8245 static void SaveTape_HEAD(FILE *file, struct TapeInfo *tape)
8246 {
8247   int i;
8248   byte store_participating_players = 0;
8249
8250   // set bits for participating players for compact storage
8251   for (i = 0; i < MAX_PLAYERS; i++)
8252     if (tape->player_participates[i])
8253       store_participating_players |= (1 << i);
8254
8255   putFile32BitBE(file, tape->random_seed);
8256   putFile32BitBE(file, tape->date);
8257   putFile32BitBE(file, tape->length);
8258
8259   putFile8Bit(file, store_participating_players);
8260
8261   putFile8Bit(file, getTapeActionValue(tape));
8262
8263   putFile8Bit(file, tape->property_bits);
8264
8265   // unused bytes not at the end here for 4-byte alignment of engine_version
8266   WriteUnusedBytesToFile(file, TAPE_CHUNK_HEAD_UNUSED);
8267
8268   putFileVersion(file, tape->engine_version);
8269 }
8270
8271 static void SaveTape_SCRN(FILE *file, struct TapeInfo *tape)
8272 {
8273   putFile8Bit(file, tape->scr_fieldx);
8274   putFile8Bit(file, tape->scr_fieldy);
8275 }
8276
8277 static void SaveTape_INFO(FILE *file, struct TapeInfo *tape)
8278 {
8279   int level_identifier_size = strlen(tape->level_identifier) + 1;
8280   int i;
8281
8282   putFile16BitBE(file, level_identifier_size);
8283
8284   for (i = 0; i < level_identifier_size; i++)
8285     putFile8Bit(file, tape->level_identifier[i]);
8286
8287   putFile16BitBE(file, tape->level_nr);
8288 }
8289
8290 static void SaveTape_BODY(FILE *file, struct TapeInfo *tape)
8291 {
8292   int i, j;
8293
8294   for (i = 0; i < tape->length; i++)
8295   {
8296     if (tape->use_key_actions)
8297     {
8298       for (j = 0; j < MAX_PLAYERS; j++)
8299         if (tape->player_participates[j])
8300           putFile8Bit(file, tape->pos[i].action[j]);
8301     }
8302
8303     if (tape->use_mouse_actions)
8304     {
8305       putFile8Bit(file, tape->pos[i].action[TAPE_ACTION_LX]);
8306       putFile8Bit(file, tape->pos[i].action[TAPE_ACTION_LY]);
8307       putFile8Bit(file, tape->pos[i].action[TAPE_ACTION_BUTTON]);
8308     }
8309
8310     putFile8Bit(file, tape->pos[i].delay);
8311   }
8312 }
8313
8314 void SaveTapeToFilename(char *filename)
8315 {
8316   FILE *file;
8317   int tape_pos_size;
8318   int info_chunk_size;
8319   int body_chunk_size;
8320
8321   if (!(file = fopen(filename, MODE_WRITE)))
8322   {
8323     Warn("cannot save level recording file '%s'", filename);
8324
8325     return;
8326   }
8327
8328   tape_pos_size = getTapePosSize(&tape);
8329
8330   info_chunk_size = 2 + (strlen(tape.level_identifier) + 1) + 2;
8331   body_chunk_size = tape_pos_size * tape.length;
8332
8333   putFileChunkBE(file, "RND1", CHUNK_SIZE_UNDEFINED);
8334   putFileChunkBE(file, "TAPE", CHUNK_SIZE_NONE);
8335
8336   putFileChunkBE(file, "VERS", TAPE_CHUNK_VERS_SIZE);
8337   SaveTape_VERS(file, &tape);
8338
8339   putFileChunkBE(file, "HEAD", TAPE_CHUNK_HEAD_SIZE);
8340   SaveTape_HEAD(file, &tape);
8341
8342   if (checkSaveTape_SCRN(&tape))
8343   {
8344     putFileChunkBE(file, "SCRN", TAPE_CHUNK_SCRN_SIZE);
8345     SaveTape_SCRN(file, &tape);
8346   }
8347
8348   putFileChunkBE(file, "INFO", info_chunk_size);
8349   SaveTape_INFO(file, &tape);
8350
8351   putFileChunkBE(file, "BODY", body_chunk_size);
8352   SaveTape_BODY(file, &tape);
8353
8354   fclose(file);
8355
8356   SetFilePermissions(filename, PERMS_PRIVATE);
8357 }
8358
8359 static void SaveTapeExt(char *filename)
8360 {
8361   int i;
8362
8363   tape.file_version = FILE_VERSION_ACTUAL;
8364   tape.game_version = GAME_VERSION_ACTUAL;
8365
8366   tape.num_participating_players = 0;
8367
8368   // count number of participating players
8369   for (i = 0; i < MAX_PLAYERS; i++)
8370     if (tape.player_participates[i])
8371       tape.num_participating_players++;
8372
8373   SaveTapeToFilename(filename);
8374
8375   tape.changed = FALSE;
8376 }
8377
8378 void SaveTape(int nr)
8379 {
8380   char *filename = getTapeFilename(nr);
8381
8382   InitTapeDirectory(leveldir_current->subdir);
8383
8384   SaveTapeExt(filename);
8385 }
8386
8387 void SaveScoreTape(int nr)
8388 {
8389   char *filename = getScoreTapeFilename(tape.score_tape_basename, nr);
8390
8391   // used instead of "leveldir_current->subdir" (for network games)
8392   InitScoreTapeDirectory(levelset.identifier, nr);
8393
8394   SaveTapeExt(filename);
8395 }
8396
8397 static boolean SaveTapeCheckedExt(int nr, char *msg_replace, char *msg_saved,
8398                                   unsigned int req_state_added)
8399 {
8400   char *filename = getTapeFilename(nr);
8401   boolean new_tape = !fileExists(filename);
8402   boolean tape_saved = FALSE;
8403
8404   if (new_tape || Request(msg_replace, REQ_ASK | req_state_added))
8405   {
8406     SaveTape(nr);
8407
8408     if (new_tape)
8409       Request(msg_saved, REQ_CONFIRM | req_state_added);
8410
8411     tape_saved = TRUE;
8412   }
8413
8414   return tape_saved;
8415 }
8416
8417 boolean SaveTapeChecked(int nr)
8418 {
8419   return SaveTapeCheckedExt(nr, "Replace old tape?", "Tape saved!", 0);
8420 }
8421
8422 boolean SaveTapeChecked_LevelSolved(int nr)
8423 {
8424   return SaveTapeCheckedExt(nr, "Level solved! Replace old tape?",
8425                                 "Level solved! Tape saved!", REQ_STAY_OPEN);
8426 }
8427
8428 void DumpTape(struct TapeInfo *tape)
8429 {
8430   int tape_frame_counter;
8431   int i, j;
8432
8433   if (tape->no_valid_file)
8434   {
8435     Warn("cannot dump -- no valid tape file found");
8436
8437     return;
8438   }
8439
8440   PrintLine("-", 79);
8441   Print("Tape of Level %03d (file version %08d, game version %08d)\n",
8442         tape->level_nr, tape->file_version, tape->game_version);
8443   Print("                  (effective engine version %08d)\n",
8444         tape->engine_version);
8445   Print("Level series identifier: '%s'\n", tape->level_identifier);
8446   PrintLine("-", 79);
8447
8448   tape_frame_counter = 0;
8449
8450   for (i = 0; i < tape->length; i++)
8451   {
8452     if (i >= MAX_TAPE_LEN)
8453       break;
8454
8455     Print("%04d: ", i);
8456
8457     for (j = 0; j < MAX_PLAYERS; j++)
8458     {
8459       if (tape->player_participates[j])
8460       {
8461         int action = tape->pos[i].action[j];
8462
8463         Print("%d:%02x ", j, action);
8464         Print("[%c%c%c%c|%c%c] - ",
8465               (action & JOY_LEFT ? '<' : ' '),
8466               (action & JOY_RIGHT ? '>' : ' '),
8467               (action & JOY_UP ? '^' : ' '),
8468               (action & JOY_DOWN ? 'v' : ' '),
8469               (action & JOY_BUTTON_1 ? '1' : ' '),
8470               (action & JOY_BUTTON_2 ? '2' : ' '));
8471       }
8472     }
8473
8474     Print("(%03d) ", tape->pos[i].delay);
8475     Print("[%05d]\n", tape_frame_counter);
8476
8477     tape_frame_counter += tape->pos[i].delay;
8478   }
8479
8480   PrintLine("-", 79);
8481 }
8482
8483 void DumpTapes(void)
8484 {
8485   static LevelDirTree *dumptape_leveldir = NULL;
8486
8487   dumptape_leveldir = getTreeInfoFromIdentifier(leveldir_first,
8488                                                 global.dumptape_leveldir);
8489
8490   if (dumptape_leveldir == NULL)
8491     Fail("no such level identifier: '%s'", global.dumptape_leveldir);
8492
8493   if (global.dumptape_level_nr < dumptape_leveldir->first_level ||
8494       global.dumptape_level_nr > dumptape_leveldir->last_level)
8495     Fail("no such level number: %d", global.dumptape_level_nr);
8496
8497   leveldir_current = dumptape_leveldir;
8498
8499   if (options.mytapes)
8500     LoadTape(global.dumptape_level_nr);
8501   else
8502     LoadSolutionTape(global.dumptape_level_nr);
8503
8504   DumpTape(&tape);
8505
8506   CloseAllAndExit(0);
8507 }
8508
8509
8510 // ============================================================================
8511 // score file functions
8512 // ============================================================================
8513
8514 static void setScoreInfoToDefaultsExt(struct ScoreInfo *scores)
8515 {
8516   int i;
8517
8518   for (i = 0; i < MAX_SCORE_ENTRIES; i++)
8519   {
8520     strcpy(scores->entry[i].tape_basename, UNDEFINED_FILENAME);
8521     strcpy(scores->entry[i].name, EMPTY_PLAYER_NAME);
8522     scores->entry[i].score = 0;
8523     scores->entry[i].time = 0;
8524   }
8525
8526   scores->num_entries = 0;
8527   scores->last_added = -1;
8528   scores->last_added_local = -1;
8529
8530   scores->updated = FALSE;
8531   scores->force_last_added = FALSE;
8532 }
8533
8534 static void setScoreInfoToDefaults(void)
8535 {
8536   setScoreInfoToDefaultsExt(&scores);
8537 }
8538
8539 static void setServerScoreInfoToDefaults(void)
8540 {
8541   setScoreInfoToDefaultsExt(&server_scores);
8542 }
8543
8544 static void LoadScore_OLD(int nr)
8545 {
8546   int i;
8547   char *filename = getScoreFilename(nr);
8548   char cookie[MAX_LINE_LEN];
8549   char line[MAX_LINE_LEN];
8550   char *line_ptr;
8551   FILE *file;
8552
8553   if (!(file = fopen(filename, MODE_READ)))
8554     return;
8555
8556   // check file identifier
8557   if (fgets(cookie, MAX_LINE_LEN, file) == NULL)
8558     cookie[0] = '\0';
8559   if (strlen(cookie) > 0 && cookie[strlen(cookie) - 1] == '\n')
8560     cookie[strlen(cookie) - 1] = '\0';
8561
8562   if (!checkCookieString(cookie, SCORE_COOKIE_TMPL))
8563   {
8564     Warn("unknown format of score file '%s'", filename);
8565
8566     fclose(file);
8567
8568     return;
8569   }
8570
8571   for (i = 0; i < MAX_SCORE_ENTRIES; i++)
8572   {
8573     if (fscanf(file, "%d", &scores.entry[i].score) == EOF)
8574       Warn("fscanf() failed; %s", strerror(errno));
8575
8576     if (fgets(line, MAX_LINE_LEN, file) == NULL)
8577       line[0] = '\0';
8578
8579     if (strlen(line) > 0 && line[strlen(line) - 1] == '\n')
8580       line[strlen(line) - 1] = '\0';
8581
8582     for (line_ptr = line; *line_ptr; line_ptr++)
8583     {
8584       if (*line_ptr != ' ' && *line_ptr != '\t' && *line_ptr != '\0')
8585       {
8586         strncpy(scores.entry[i].name, line_ptr, MAX_PLAYER_NAME_LEN);
8587         scores.entry[i].name[MAX_PLAYER_NAME_LEN] = '\0';
8588         break;
8589       }
8590     }
8591   }
8592
8593   fclose(file);
8594 }
8595
8596 static void ConvertScore_OLD(void)
8597 {
8598   // only convert score to time for levels that rate playing time over score
8599   if (!level.rate_time_over_score)
8600     return;
8601
8602   // convert old score to playing time for score-less levels (like Supaplex)
8603   int time_final_max = 999;
8604   int i;
8605
8606   for (i = 0; i < MAX_SCORE_ENTRIES; i++)
8607   {
8608     int score = scores.entry[i].score;
8609
8610     if (score > 0 && score < time_final_max)
8611       scores.entry[i].time = (time_final_max - score - 1) * FRAMES_PER_SECOND;
8612   }
8613 }
8614
8615 static int LoadScore_VERS(File *file, int chunk_size, struct ScoreInfo *scores)
8616 {
8617   scores->file_version = getFileVersion(file);
8618   scores->game_version = getFileVersion(file);
8619
8620   return chunk_size;
8621 }
8622
8623 static int LoadScore_INFO(File *file, int chunk_size, struct ScoreInfo *scores)
8624 {
8625   char *level_identifier = NULL;
8626   int level_identifier_size;
8627   int i;
8628
8629   level_identifier_size = getFile16BitBE(file);
8630
8631   level_identifier = checked_malloc(level_identifier_size);
8632
8633   for (i = 0; i < level_identifier_size; i++)
8634     level_identifier[i] = getFile8Bit(file);
8635
8636   strncpy(scores->level_identifier, level_identifier, MAX_FILENAME_LEN);
8637   scores->level_identifier[MAX_FILENAME_LEN] = '\0';
8638
8639   checked_free(level_identifier);
8640
8641   scores->level_nr = getFile16BitBE(file);
8642   scores->num_entries = getFile16BitBE(file);
8643
8644   chunk_size = 2 + level_identifier_size + 2 + 2;
8645
8646   return chunk_size;
8647 }
8648
8649 static int LoadScore_NAME(File *file, int chunk_size, struct ScoreInfo *scores)
8650 {
8651   int i, j;
8652
8653   for (i = 0; i < scores->num_entries; i++)
8654   {
8655     for (j = 0; j < MAX_PLAYER_NAME_LEN; j++)
8656       scores->entry[i].name[j] = getFile8Bit(file);
8657
8658     scores->entry[i].name[MAX_PLAYER_NAME_LEN] = '\0';
8659   }
8660
8661   chunk_size = scores->num_entries * MAX_PLAYER_NAME_LEN;
8662
8663   return chunk_size;
8664 }
8665
8666 static int LoadScore_SCOR(File *file, int chunk_size, struct ScoreInfo *scores)
8667 {
8668   int i;
8669
8670   for (i = 0; i < scores->num_entries; i++)
8671     scores->entry[i].score = getFile16BitBE(file);
8672
8673   chunk_size = scores->num_entries * 2;
8674
8675   return chunk_size;
8676 }
8677
8678 static int LoadScore_TIME(File *file, int chunk_size, struct ScoreInfo *scores)
8679 {
8680   int i;
8681
8682   for (i = 0; i < scores->num_entries; i++)
8683     scores->entry[i].time = getFile32BitBE(file);
8684
8685   chunk_size = scores->num_entries * 4;
8686
8687   return chunk_size;
8688 }
8689
8690 static int LoadScore_TAPE(File *file, int chunk_size, struct ScoreInfo *scores)
8691 {
8692   int i, j;
8693
8694   for (i = 0; i < scores->num_entries; i++)
8695   {
8696     for (j = 0; j < MAX_SCORE_TAPE_BASENAME_LEN; j++)
8697       scores->entry[i].tape_basename[j] = getFile8Bit(file);
8698
8699     scores->entry[i].tape_basename[MAX_SCORE_TAPE_BASENAME_LEN] = '\0';
8700   }
8701
8702   chunk_size = scores->num_entries * MAX_SCORE_TAPE_BASENAME_LEN;
8703
8704   return chunk_size;
8705 }
8706
8707 void LoadScore(int nr)
8708 {
8709   char *filename = getScoreFilename(nr);
8710   char cookie[MAX_LINE_LEN];
8711   char chunk_name[CHUNK_ID_LEN + 1];
8712   int chunk_size;
8713   boolean old_score_file_format = FALSE;
8714   File *file;
8715
8716   // always start with reliable default values
8717   setScoreInfoToDefaults();
8718
8719   if (!(file = openFile(filename, MODE_READ)))
8720     return;
8721
8722   getFileChunkBE(file, chunk_name, NULL);
8723   if (strEqual(chunk_name, "RND1"))
8724   {
8725     getFile32BitBE(file);               // not used
8726
8727     getFileChunkBE(file, chunk_name, NULL);
8728     if (!strEqual(chunk_name, "SCOR"))
8729     {
8730       Warn("unknown format of score file '%s'", filename);
8731
8732       closeFile(file);
8733
8734       return;
8735     }
8736   }
8737   else  // check for old file format with cookie string
8738   {
8739     strcpy(cookie, chunk_name);
8740     if (getStringFromFile(file, &cookie[4], MAX_LINE_LEN - 4) == NULL)
8741       cookie[4] = '\0';
8742     if (strlen(cookie) > 0 && cookie[strlen(cookie) - 1] == '\n')
8743       cookie[strlen(cookie) - 1] = '\0';
8744
8745     if (!checkCookieString(cookie, SCORE_COOKIE_TMPL))
8746     {
8747       Warn("unknown format of score file '%s'", filename);
8748
8749       closeFile(file);
8750
8751       return;
8752     }
8753
8754     old_score_file_format = TRUE;
8755   }
8756
8757   if (old_score_file_format)
8758   {
8759     // score files from versions before 4.2.4.0 without chunk structure
8760     LoadScore_OLD(nr);
8761
8762     // convert score to time, if possible (mainly for Supaplex levels)
8763     ConvertScore_OLD();
8764   }
8765   else
8766   {
8767     static struct
8768     {
8769       char *name;
8770       int size;
8771       int (*loader)(File *, int, struct ScoreInfo *);
8772     }
8773     chunk_info[] =
8774     {
8775       { "VERS", SCORE_CHUNK_VERS_SIZE,  LoadScore_VERS },
8776       { "INFO", -1,                     LoadScore_INFO },
8777       { "NAME", -1,                     LoadScore_NAME },
8778       { "SCOR", -1,                     LoadScore_SCOR },
8779       { "TIME", -1,                     LoadScore_TIME },
8780       { "TAPE", -1,                     LoadScore_TAPE },
8781
8782       {  NULL,  0,                      NULL }
8783     };
8784
8785     while (getFileChunkBE(file, chunk_name, &chunk_size))
8786     {
8787       int i = 0;
8788
8789       while (chunk_info[i].name != NULL &&
8790              !strEqual(chunk_name, chunk_info[i].name))
8791         i++;
8792
8793       if (chunk_info[i].name == NULL)
8794       {
8795         Warn("unknown chunk '%s' in score file '%s'",
8796               chunk_name, filename);
8797
8798         ReadUnusedBytesFromFile(file, chunk_size);
8799       }
8800       else if (chunk_info[i].size != -1 &&
8801                chunk_info[i].size != chunk_size)
8802       {
8803         Warn("wrong size (%d) of chunk '%s' in score file '%s'",
8804               chunk_size, chunk_name, filename);
8805
8806         ReadUnusedBytesFromFile(file, chunk_size);
8807       }
8808       else
8809       {
8810         // call function to load this score chunk
8811         int chunk_size_expected =
8812           (chunk_info[i].loader)(file, chunk_size, &scores);
8813
8814         // the size of some chunks cannot be checked before reading other
8815         // chunks first (like "HEAD" and "BODY") that contain some header
8816         // information, so check them here
8817         if (chunk_size_expected != chunk_size)
8818         {
8819           Warn("wrong size (%d) of chunk '%s' in score file '%s'",
8820                 chunk_size, chunk_name, filename);
8821         }
8822       }
8823     }
8824   }
8825
8826   closeFile(file);
8827 }
8828
8829 #if ENABLE_HISTORIC_CHUNKS
8830 void SaveScore_OLD(int nr)
8831 {
8832   int i;
8833   char *filename = getScoreFilename(nr);
8834   FILE *file;
8835
8836   // used instead of "leveldir_current->subdir" (for network games)
8837   InitScoreDirectory(levelset.identifier);
8838
8839   if (!(file = fopen(filename, MODE_WRITE)))
8840   {
8841     Warn("cannot save score for level %d", nr);
8842
8843     return;
8844   }
8845
8846   fprintf(file, "%s\n\n", SCORE_COOKIE);
8847
8848   for (i = 0; i < MAX_SCORE_ENTRIES; i++)
8849     fprintf(file, "%d %s\n", scores.entry[i].score, scores.entry[i].name);
8850
8851   fclose(file);
8852
8853   SetFilePermissions(filename, PERMS_PRIVATE);
8854 }
8855 #endif
8856
8857 static void SaveScore_VERS(FILE *file, struct ScoreInfo *scores)
8858 {
8859   putFileVersion(file, scores->file_version);
8860   putFileVersion(file, scores->game_version);
8861 }
8862
8863 static void SaveScore_INFO(FILE *file, struct ScoreInfo *scores)
8864 {
8865   int level_identifier_size = strlen(scores->level_identifier) + 1;
8866   int i;
8867
8868   putFile16BitBE(file, level_identifier_size);
8869
8870   for (i = 0; i < level_identifier_size; i++)
8871     putFile8Bit(file, scores->level_identifier[i]);
8872
8873   putFile16BitBE(file, scores->level_nr);
8874   putFile16BitBE(file, scores->num_entries);
8875 }
8876
8877 static void SaveScore_NAME(FILE *file, struct ScoreInfo *scores)
8878 {
8879   int i, j;
8880
8881   for (i = 0; i < scores->num_entries; i++)
8882   {
8883     int name_size = strlen(scores->entry[i].name);
8884
8885     for (j = 0; j < MAX_PLAYER_NAME_LEN; j++)
8886       putFile8Bit(file, (j < name_size ? scores->entry[i].name[j] : 0));
8887   }
8888 }
8889
8890 static void SaveScore_SCOR(FILE *file, struct ScoreInfo *scores)
8891 {
8892   int i;
8893
8894   for (i = 0; i < scores->num_entries; i++)
8895     putFile16BitBE(file, scores->entry[i].score);
8896 }
8897
8898 static void SaveScore_TIME(FILE *file, struct ScoreInfo *scores)
8899 {
8900   int i;
8901
8902   for (i = 0; i < scores->num_entries; i++)
8903     putFile32BitBE(file, scores->entry[i].time);
8904 }
8905
8906 static void SaveScore_TAPE(FILE *file, struct ScoreInfo *scores)
8907 {
8908   int i, j;
8909
8910   for (i = 0; i < scores->num_entries; i++)
8911   {
8912     int size = strlen(scores->entry[i].tape_basename);
8913
8914     for (j = 0; j < MAX_SCORE_TAPE_BASENAME_LEN; j++)
8915       putFile8Bit(file, (j < size ? scores->entry[i].tape_basename[j] : 0));
8916   }
8917 }
8918
8919 static void SaveScoreToFilename(char *filename)
8920 {
8921   FILE *file;
8922   int info_chunk_size;
8923   int name_chunk_size;
8924   int scor_chunk_size;
8925   int time_chunk_size;
8926   int tape_chunk_size;
8927
8928   if (!(file = fopen(filename, MODE_WRITE)))
8929   {
8930     Warn("cannot save score file '%s'", filename);
8931
8932     return;
8933   }
8934
8935   info_chunk_size = 2 + (strlen(scores.level_identifier) + 1) + 2 + 2;
8936   name_chunk_size = scores.num_entries * MAX_PLAYER_NAME_LEN;
8937   scor_chunk_size = scores.num_entries * 2;
8938   time_chunk_size = scores.num_entries * 4;
8939   tape_chunk_size = scores.num_entries * MAX_SCORE_TAPE_BASENAME_LEN;
8940
8941   putFileChunkBE(file, "RND1", CHUNK_SIZE_UNDEFINED);
8942   putFileChunkBE(file, "SCOR", CHUNK_SIZE_NONE);
8943
8944   putFileChunkBE(file, "VERS", SCORE_CHUNK_VERS_SIZE);
8945   SaveScore_VERS(file, &scores);
8946
8947   putFileChunkBE(file, "INFO", info_chunk_size);
8948   SaveScore_INFO(file, &scores);
8949
8950   putFileChunkBE(file, "NAME", name_chunk_size);
8951   SaveScore_NAME(file, &scores);
8952
8953   putFileChunkBE(file, "SCOR", scor_chunk_size);
8954   SaveScore_SCOR(file, &scores);
8955
8956   putFileChunkBE(file, "TIME", time_chunk_size);
8957   SaveScore_TIME(file, &scores);
8958
8959   putFileChunkBE(file, "TAPE", tape_chunk_size);
8960   SaveScore_TAPE(file, &scores);
8961
8962   fclose(file);
8963
8964   SetFilePermissions(filename, PERMS_PRIVATE);
8965 }
8966
8967 void SaveScore(int nr)
8968 {
8969   char *filename = getScoreFilename(nr);
8970   int i;
8971
8972   // used instead of "leveldir_current->subdir" (for network games)
8973   InitScoreDirectory(levelset.identifier);
8974
8975   scores.file_version = FILE_VERSION_ACTUAL;
8976   scores.game_version = GAME_VERSION_ACTUAL;
8977
8978   strncpy(scores.level_identifier, levelset.identifier, MAX_FILENAME_LEN);
8979   scores.level_identifier[MAX_FILENAME_LEN] = '\0';
8980   scores.level_nr = level_nr;
8981
8982   for (i = 0; i < MAX_SCORE_ENTRIES; i++)
8983     if (scores.entry[i].score == 0 &&
8984         scores.entry[i].time == 0 &&
8985         strEqual(scores.entry[i].name, EMPTY_PLAYER_NAME))
8986       break;
8987
8988   scores.num_entries = i;
8989
8990   if (scores.num_entries == 0)
8991     return;
8992
8993   SaveScoreToFilename(filename);
8994 }
8995
8996 static void ExecuteAsThread(SDL_ThreadFunction function, char *name, int data,
8997                             char *error)
8998 {
8999   static int data_static;
9000
9001   data_static = data;
9002
9003   SDL_Thread *thread = SDL_CreateThread(function, name, &data_static);
9004
9005   if (thread != NULL)
9006     SDL_DetachThread(thread);
9007   else
9008     Error("Cannot create thread to %s!", error);
9009
9010   // nasty kludge to lower probability of intermingled thread error messages
9011   Delay(1);
9012 }
9013
9014 static void DownloadServerScoreToCacheExt(struct HttpRequest *request,
9015                                           struct HttpResponse *response,
9016                                           int nr)
9017 {
9018   request->hostname = setup.api_server_hostname;
9019   request->port     = API_SERVER_PORT;
9020   request->method   = API_SERVER_METHOD;
9021   request->uri      = API_SERVER_URI_GET;
9022
9023   snprintf(request->body, MAX_HTTP_BODY_SIZE,
9024            "{\n"
9025            "  \"levelset_identifier\":  \"%s\",\n"
9026            "  \"level_nr\":             \"%d\",\n"
9027            "  \"rate_time_over_score\": \"%d\"\n"
9028            "}\n",
9029            levelset.identifier, nr, level.rate_time_over_score);
9030
9031   if (!DoHttpRequest(request, response))
9032   {
9033     Error("HTTP request failed: %s", GetHttpError());
9034
9035     return;
9036   }
9037
9038   if (!HTTP_SUCCESS(response->status_code))
9039   {
9040     Error("server failed to handle request: %d %s",
9041           response->status_code,
9042           response->status_text);
9043
9044     return;
9045   }
9046
9047   if (response->body_size == 0)
9048   {
9049     // no scores available for this level
9050
9051     return;
9052   }
9053
9054   ConvertHttpResponseBodyToClientEncoding(response);
9055
9056   char *filename = getScoreCacheFilename(nr);
9057   FILE *file;
9058   int i;
9059
9060   // used instead of "leveldir_current->subdir" (for network games)
9061   InitScoreCacheDirectory(levelset.identifier);
9062
9063   if (!(file = fopen(filename, MODE_WRITE)))
9064   {
9065     Warn("cannot save score cache file '%s'", filename);
9066
9067     return;
9068   }
9069
9070   for (i = 0; i < response->body_size; i++)
9071     fputc(response->body[i], file);
9072
9073   fclose(file);
9074
9075   SetFilePermissions(filename, PERMS_PRIVATE);
9076
9077   server_scores.updated = TRUE;
9078 }
9079
9080 static void DownloadServerScoreToCache(int nr)
9081 {
9082   struct HttpRequest *request = checked_calloc(sizeof(struct HttpRequest));
9083   struct HttpResponse *response = checked_calloc(sizeof(struct HttpResponse));
9084
9085   DownloadServerScoreToCacheExt(request, response, nr);
9086
9087   checked_free(request);
9088   checked_free(response);
9089 }
9090
9091 static int DownloadServerScoreToCacheThread(void *data)
9092 {
9093   DownloadServerScoreToCache(*(int *)data);
9094
9095   return 0;
9096 }
9097
9098 static void DownloadServerScoreToCacheAsThread(int nr)
9099 {
9100   ExecuteAsThread(DownloadServerScoreToCacheThread,
9101                   "DownloadServerScoreToCache", nr,
9102                   "download scores from server");
9103 }
9104
9105 static void LoadServerScoreFromCache(int nr)
9106 {
9107   struct ScoreEntry score_entry;
9108   struct
9109   {
9110     void *value;
9111     boolean is_string;
9112     int string_size;
9113   }
9114   score_mapping[] =
9115   {
9116     { &score_entry.score,               FALSE,  0                       },
9117     { &score_entry.time,                FALSE,  0                       },
9118     { score_entry.name,                 TRUE,   MAX_PLAYER_NAME_LEN     },
9119     { score_entry.tape_basename,        TRUE,   MAX_FILENAME_LEN        },
9120
9121     { NULL,                             FALSE,  0                       }
9122   };
9123   char *filename = getScoreCacheFilename(nr);
9124   SetupFileHash *score_hash = loadSetupFileHash(filename);
9125   int i, j;
9126
9127   server_scores.num_entries = 0;
9128
9129   if (score_hash == NULL)
9130     return;
9131
9132   for (i = 0; i < MAX_SCORE_ENTRIES; i++)
9133   {
9134     score_entry = server_scores.entry[i];
9135
9136     for (j = 0; score_mapping[j].value != NULL; j++)
9137     {
9138       char token[10];
9139
9140       sprintf(token, "%02d.%d", i, j);
9141
9142       char *value = getHashEntry(score_hash, token);
9143
9144       if (value == NULL)
9145         continue;
9146
9147       if (score_mapping[j].is_string)
9148       {
9149         char *score_value = (char *)score_mapping[j].value;
9150         int value_size = score_mapping[j].string_size;
9151
9152         strncpy(score_value, value, value_size);
9153         score_value[value_size] = '\0';
9154       }
9155       else
9156       {
9157         int *score_value = (int *)score_mapping[j].value;
9158
9159         *score_value = atoi(value);
9160       }
9161
9162       server_scores.num_entries = i + 1;
9163     }
9164
9165     server_scores.entry[i] = score_entry;
9166   }
9167
9168   freeSetupFileHash(score_hash);
9169 }
9170
9171 void LoadServerScore(int nr, boolean download_score)
9172 {
9173   if (!setup.api_server)
9174     return;
9175
9176   // always start with reliable default values
9177   setServerScoreInfoToDefaults();
9178
9179   // 1st step: load server scores from cache file (which may not exist)
9180   // (this should prevent reading it while the thread is writing to it)
9181   LoadServerScoreFromCache(nr);
9182
9183   if (download_score && runtime.api_server)
9184   {
9185     // 2nd step: download server scores from score server to cache file
9186     // (as thread, as it might time out if the server is not reachable)
9187     DownloadServerScoreToCacheAsThread(nr);
9188   }
9189 }
9190
9191 static char *get_file_base64(char *filename)
9192 {
9193   struct stat file_status;
9194
9195   if (stat(filename, &file_status) != 0)
9196   {
9197     Error("cannot stat file '%s'\n", filename);
9198
9199     return NULL;
9200   }
9201
9202   int buffer_size = file_status.st_size;
9203   byte *buffer = checked_malloc(buffer_size);
9204   FILE *file;
9205   int i;
9206
9207   if (!(file = fopen(filename, MODE_READ)))
9208   {
9209     Error("cannot open file '%s'\n", filename);
9210
9211     checked_free(buffer);
9212
9213     return NULL;
9214   }
9215
9216   for (i = 0; i < buffer_size; i++)
9217   {
9218     int c = fgetc(file);
9219
9220     if (c == EOF)
9221     {
9222       Error("cannot read from input file '%s'\n", filename);
9223
9224       fclose(file);
9225       checked_free(buffer);
9226
9227       return NULL;
9228     }
9229
9230     buffer[i] = (byte)c;
9231   }
9232
9233   fclose(file);
9234
9235   int buffer_encoded_size = base64_encoded_size(buffer_size);
9236   char *buffer_encoded = checked_malloc(buffer_encoded_size);
9237
9238   base64_encode(buffer_encoded, buffer, buffer_size);
9239
9240   checked_free(buffer);
9241
9242   return buffer_encoded;
9243 }
9244
9245 static void UploadScoreToServerExt(struct HttpRequest *request,
9246                                    struct HttpResponse *response,
9247                                    int nr)
9248 {
9249   struct ScoreEntry *score_entry = &scores.entry[scores.last_added];
9250
9251   request->hostname = setup.api_server_hostname;
9252   request->port     = API_SERVER_PORT;
9253   request->method   = API_SERVER_METHOD;
9254   request->uri      = API_SERVER_URI_ADD;
9255
9256   char *tape_filename = getScoreTapeFilename(score_entry->tape_basename, nr);
9257   char *tape_base64 = get_file_base64(tape_filename);
9258
9259   if (tape_base64 == NULL)
9260   {
9261     Error("loading and base64 encoding score tape file failed");
9262
9263     return;
9264   }
9265
9266   snprintf(request->body, MAX_HTTP_BODY_SIZE,
9267            "{\n"
9268            "  \"game_version\":         \"%s\",\n"
9269            "  \"levelset_identifier\":  \"%s\",\n"
9270            "  \"levelset_name\":        \"%s\",\n"
9271            "  \"levelset_author\":      \"%s\",\n"
9272            "  \"levelset_num_levels\":  \"%d\",\n"
9273            "  \"levelset_first_level\": \"%d\",\n"
9274            "  \"level_nr\":             \"%d\",\n"
9275            "  \"player_name\":          \"%s\",\n"
9276            "  \"score\":                \"%d\",\n"
9277            "  \"time\":                 \"%d\",\n"
9278            "  \"tape_basename\":        \"%s\",\n"
9279            "  \"tape\":                 \"%s\"\n"
9280            "}\n",
9281            getProgramRealVersionString(),
9282            leveldir_current->identifier,
9283            leveldir_current->name,
9284            leveldir_current->author,
9285            leveldir_current->levels,
9286            leveldir_current->first_level,
9287            level_nr,
9288            score_entry->name,
9289            score_entry->score,
9290            score_entry->time,
9291            score_entry->tape_basename,
9292            tape_base64);
9293
9294   checked_free(tape_base64);
9295
9296   ConvertHttpRequestBodyToServerEncoding(request);
9297
9298   if (!DoHttpRequest(request, response))
9299   {
9300     Error("HTTP request failed: %s", GetHttpError());
9301
9302     return;
9303   }
9304
9305   if (!HTTP_SUCCESS(response->status_code))
9306   {
9307     Error("server failed to handle request: %d %s",
9308           response->status_code,
9309           response->status_text);
9310
9311     return;
9312   }
9313 }
9314
9315 static void UploadScoreToServer(int nr)
9316 {
9317   struct HttpRequest *request = checked_calloc(sizeof(struct HttpRequest));
9318   struct HttpResponse *response = checked_calloc(sizeof(struct HttpResponse));
9319
9320   UploadScoreToServerExt(request, response, nr);
9321
9322   checked_free(request);
9323   checked_free(response);
9324 }
9325
9326 static int UploadScoreToServerThread(void *data)
9327 {
9328   UploadScoreToServer(*(int *)data);
9329
9330   return 0;
9331 }
9332
9333 static void UploadScoreToServerAsThread(int nr)
9334 {
9335   ExecuteAsThread(UploadScoreToServerThread,
9336                   "UploadScoreToServer", nr,
9337                   "upload score to server");
9338 }
9339
9340 void SaveServerScore(int nr)
9341 {
9342   if (!runtime.api_server)
9343     return;
9344
9345   UploadScoreToServerAsThread(nr);
9346 }
9347
9348 void LoadLocalAndServerScore(int nr, boolean download_score)
9349 {
9350   int last_added_local = scores.last_added_local;
9351
9352   LoadScore(nr);
9353
9354   // restore last added local score entry (before merging server scores)
9355   scores.last_added = scores.last_added_local = last_added_local;
9356
9357   if (setup.api_server && !setup.only_show_local_scores)
9358   {
9359     // load server scores from cache file and trigger update from server
9360     LoadServerScore(nr, download_score);
9361
9362     // merge local scores with scores from server
9363     MergeServerScore();
9364   }
9365 }
9366
9367
9368 // ============================================================================
9369 // setup file functions
9370 // ============================================================================
9371
9372 #define TOKEN_STR_PLAYER_PREFIX                 "player_"
9373
9374
9375 static struct TokenInfo global_setup_tokens[] =
9376 {
9377   {
9378     TYPE_STRING,
9379     &setup.player_name,                         "player_name"
9380   },
9381   {
9382     TYPE_SWITCH,
9383     &setup.multiple_users,                      "multiple_users"
9384   },
9385   {
9386     TYPE_SWITCH,
9387     &setup.sound,                               "sound"
9388   },
9389   {
9390     TYPE_SWITCH,
9391     &setup.sound_loops,                         "repeating_sound_loops"
9392   },
9393   {
9394     TYPE_SWITCH,
9395     &setup.sound_music,                         "background_music"
9396   },
9397   {
9398     TYPE_SWITCH,
9399     &setup.sound_simple,                        "simple_sound_effects"
9400   },
9401   {
9402     TYPE_SWITCH,
9403     &setup.toons,                               "toons"
9404   },
9405   {
9406     TYPE_SWITCH,
9407     &setup.scroll_delay,                        "scroll_delay"
9408   },
9409   {
9410     TYPE_SWITCH,
9411     &setup.forced_scroll_delay,                 "forced_scroll_delay"
9412   },
9413   {
9414     TYPE_INTEGER,
9415     &setup.scroll_delay_value,                  "scroll_delay_value"
9416   },
9417   {
9418     TYPE_STRING,
9419     &setup.engine_snapshot_mode,                "engine_snapshot_mode"
9420   },
9421   {
9422     TYPE_INTEGER,
9423     &setup.engine_snapshot_memory,              "engine_snapshot_memory"
9424   },
9425   {
9426     TYPE_SWITCH,
9427     &setup.fade_screens,                        "fade_screens"
9428   },
9429   {
9430     TYPE_SWITCH,
9431     &setup.autorecord,                          "automatic_tape_recording"
9432   },
9433   {
9434     TYPE_SWITCH,
9435     &setup.show_titlescreen,                    "show_titlescreen"
9436   },
9437   {
9438     TYPE_SWITCH,
9439     &setup.quick_doors,                         "quick_doors"
9440   },
9441   {
9442     TYPE_SWITCH,
9443     &setup.team_mode,                           "team_mode"
9444   },
9445   {
9446     TYPE_SWITCH,
9447     &setup.handicap,                            "handicap"
9448   },
9449   {
9450     TYPE_SWITCH,
9451     &setup.skip_levels,                         "skip_levels"
9452   },
9453   {
9454     TYPE_SWITCH,
9455     &setup.increment_levels,                    "increment_levels"
9456   },
9457   {
9458     TYPE_SWITCH,
9459     &setup.auto_play_next_level,                "auto_play_next_level"
9460   },
9461   {
9462     TYPE_SWITCH,
9463     &setup.count_score_after_game,              "count_score_after_game"
9464   },
9465   {
9466     TYPE_SWITCH,
9467     &setup.show_scores_after_game,              "show_scores_after_game"
9468   },
9469   {
9470     TYPE_SWITCH,
9471     &setup.time_limit,                          "time_limit"
9472   },
9473   {
9474     TYPE_SWITCH,
9475     &setup.fullscreen,                          "fullscreen"
9476   },
9477   {
9478     TYPE_INTEGER,
9479     &setup.window_scaling_percent,              "window_scaling_percent"
9480   },
9481   {
9482     TYPE_STRING,
9483     &setup.window_scaling_quality,              "window_scaling_quality"
9484   },
9485   {
9486     TYPE_STRING,
9487     &setup.screen_rendering_mode,               "screen_rendering_mode"
9488   },
9489   {
9490     TYPE_STRING,
9491     &setup.vsync_mode,                          "vsync_mode"
9492   },
9493   {
9494     TYPE_SWITCH,
9495     &setup.ask_on_escape,                       "ask_on_escape"
9496   },
9497   {
9498     TYPE_SWITCH,
9499     &setup.ask_on_escape_editor,                "ask_on_escape_editor"
9500   },
9501   {
9502     TYPE_SWITCH,
9503     &setup.ask_on_game_over,                    "ask_on_game_over"
9504   },
9505   {
9506     TYPE_SWITCH,
9507     &setup.ask_on_quit_game,                    "ask_on_quit_game"
9508   },
9509   {
9510     TYPE_SWITCH,
9511     &setup.ask_on_quit_program,                 "ask_on_quit_program"
9512   },
9513   {
9514     TYPE_SWITCH,
9515     &setup.quick_switch,                        "quick_player_switch"
9516   },
9517   {
9518     TYPE_SWITCH,
9519     &setup.input_on_focus,                      "input_on_focus"
9520   },
9521   {
9522     TYPE_SWITCH,
9523     &setup.prefer_aga_graphics,                 "prefer_aga_graphics"
9524   },
9525   {
9526     TYPE_SWITCH,
9527     &setup.prefer_lowpass_sounds,               "prefer_lowpass_sounds"
9528   },
9529   {
9530     TYPE_SWITCH,
9531     &setup.prefer_extra_panel_items,            "prefer_extra_panel_items"
9532   },
9533   {
9534     TYPE_SWITCH,
9535     &setup.game_speed_extended,                 "game_speed_extended"
9536   },
9537   {
9538     TYPE_INTEGER,
9539     &setup.game_frame_delay,                    "game_frame_delay"
9540   },
9541   {
9542     TYPE_SWITCH,
9543     &setup.sp_show_border_elements,             "sp_show_border_elements"
9544   },
9545   {
9546     TYPE_SWITCH,
9547     &setup.small_game_graphics,                 "small_game_graphics"
9548   },
9549   {
9550     TYPE_SWITCH,
9551     &setup.show_snapshot_buttons,               "show_snapshot_buttons"
9552   },
9553   {
9554     TYPE_SWITCH,
9555     &setup.only_show_local_scores,              "only_show_local_scores"
9556   },
9557   {
9558     TYPE_STRING,
9559     &setup.graphics_set,                        "graphics_set"
9560   },
9561   {
9562     TYPE_STRING,
9563     &setup.sounds_set,                          "sounds_set"
9564   },
9565   {
9566     TYPE_STRING,
9567     &setup.music_set,                           "music_set"
9568   },
9569   {
9570     TYPE_SWITCH3,
9571     &setup.override_level_graphics,             "override_level_graphics"
9572   },
9573   {
9574     TYPE_SWITCH3,
9575     &setup.override_level_sounds,               "override_level_sounds"
9576   },
9577   {
9578     TYPE_SWITCH3,
9579     &setup.override_level_music,                "override_level_music"
9580   },
9581   {
9582     TYPE_INTEGER,
9583     &setup.volume_simple,                       "volume_simple"
9584   },
9585   {
9586     TYPE_INTEGER,
9587     &setup.volume_loops,                        "volume_loops"
9588   },
9589   {
9590     TYPE_INTEGER,
9591     &setup.volume_music,                        "volume_music"
9592   },
9593   {
9594     TYPE_SWITCH,
9595     &setup.network_mode,                        "network_mode"
9596   },
9597   {
9598     TYPE_PLAYER,
9599     &setup.network_player_nr,                   "network_player"
9600   },
9601   {
9602     TYPE_STRING,
9603     &setup.network_server_hostname,             "network_server_hostname"
9604   },
9605   {
9606     TYPE_SWITCH,
9607     &setup.api_server,                          "api_server"
9608   },
9609   {
9610     TYPE_STRING,
9611     &setup.api_server_hostname,                 "api_server_hostname"
9612   },
9613   {
9614     TYPE_STRING,
9615     &setup.touch.control_type,                  "touch.control_type"
9616   },
9617   {
9618     TYPE_INTEGER,
9619     &setup.touch.move_distance,                 "touch.move_distance"
9620   },
9621   {
9622     TYPE_INTEGER,
9623     &setup.touch.drop_distance,                 "touch.drop_distance"
9624   },
9625   {
9626     TYPE_INTEGER,
9627     &setup.touch.transparency,                  "touch.transparency"
9628   },
9629   {
9630     TYPE_INTEGER,
9631     &setup.touch.draw_outlined,                 "touch.draw_outlined"
9632   },
9633   {
9634     TYPE_INTEGER,
9635     &setup.touch.draw_pressed,                  "touch.draw_pressed"
9636   },
9637   {
9638     TYPE_INTEGER,
9639     &setup.touch.grid_xsize[0],                 "touch.virtual_buttons.0.xsize"
9640   },
9641   {
9642     TYPE_INTEGER,
9643     &setup.touch.grid_ysize[0],                 "touch.virtual_buttons.0.ysize"
9644   },
9645   {
9646     TYPE_INTEGER,
9647     &setup.touch.grid_xsize[1],                 "touch.virtual_buttons.1.xsize"
9648   },
9649   {
9650     TYPE_INTEGER,
9651     &setup.touch.grid_ysize[1],                 "touch.virtual_buttons.1.ysize"
9652   },
9653 };
9654
9655 static struct TokenInfo auto_setup_tokens[] =
9656 {
9657   {
9658     TYPE_INTEGER,
9659     &setup.auto_setup.editor_zoom_tilesize,     "editor.zoom_tilesize"
9660   },
9661 };
9662
9663 static struct TokenInfo editor_setup_tokens[] =
9664 {
9665   {
9666     TYPE_SWITCH,
9667     &setup.editor.el_classic,                   "editor.el_classic"
9668   },
9669   {
9670     TYPE_SWITCH,
9671     &setup.editor.el_custom,                    "editor.el_custom"
9672   },
9673   {
9674     TYPE_SWITCH,
9675     &setup.editor.el_user_defined,              "editor.el_user_defined"
9676   },
9677   {
9678     TYPE_SWITCH,
9679     &setup.editor.el_dynamic,                   "editor.el_dynamic"
9680   },
9681   {
9682     TYPE_SWITCH,
9683     &setup.editor.el_headlines,                 "editor.el_headlines"
9684   },
9685   {
9686     TYPE_SWITCH,
9687     &setup.editor.show_element_token,           "editor.show_element_token"
9688   },
9689   {
9690     TYPE_SWITCH,
9691     &setup.editor.show_read_only_warning,       "editor.show_read_only_warning"
9692   },
9693 };
9694
9695 static struct TokenInfo editor_cascade_setup_tokens[] =
9696 {
9697   {
9698     TYPE_SWITCH,
9699     &setup.editor_cascade.el_bd,                "editor.cascade.el_bd"
9700   },
9701   {
9702     TYPE_SWITCH,
9703     &setup.editor_cascade.el_em,                "editor.cascade.el_em"
9704   },
9705   {
9706     TYPE_SWITCH,
9707     &setup.editor_cascade.el_emc,               "editor.cascade.el_emc"
9708   },
9709   {
9710     TYPE_SWITCH,
9711     &setup.editor_cascade.el_rnd,               "editor.cascade.el_rnd"
9712   },
9713   {
9714     TYPE_SWITCH,
9715     &setup.editor_cascade.el_sb,                "editor.cascade.el_sb"
9716   },
9717   {
9718     TYPE_SWITCH,
9719     &setup.editor_cascade.el_sp,                "editor.cascade.el_sp"
9720   },
9721   {
9722     TYPE_SWITCH,
9723     &setup.editor_cascade.el_dc,                "editor.cascade.el_dc"
9724   },
9725   {
9726     TYPE_SWITCH,
9727     &setup.editor_cascade.el_dx,                "editor.cascade.el_dx"
9728   },
9729   {
9730     TYPE_SWITCH,
9731     &setup.editor_cascade.el_mm,                "editor.cascade.el_mm"
9732   },
9733   {
9734     TYPE_SWITCH,
9735     &setup.editor_cascade.el_df,                "editor.cascade.el_df"
9736   },
9737   {
9738     TYPE_SWITCH,
9739     &setup.editor_cascade.el_chars,             "editor.cascade.el_chars"
9740   },
9741   {
9742     TYPE_SWITCH,
9743     &setup.editor_cascade.el_steel_chars,       "editor.cascade.el_steel_chars"
9744   },
9745   {
9746     TYPE_SWITCH,
9747     &setup.editor_cascade.el_ce,                "editor.cascade.el_ce"
9748   },
9749   {
9750     TYPE_SWITCH,
9751     &setup.editor_cascade.el_ge,                "editor.cascade.el_ge"
9752   },
9753   {
9754     TYPE_SWITCH,
9755     &setup.editor_cascade.el_ref,               "editor.cascade.el_ref"
9756   },
9757   {
9758     TYPE_SWITCH,
9759     &setup.editor_cascade.el_user,              "editor.cascade.el_user"
9760   },
9761   {
9762     TYPE_SWITCH,
9763     &setup.editor_cascade.el_dynamic,           "editor.cascade.el_dynamic"
9764   },
9765 };
9766
9767 static struct TokenInfo shortcut_setup_tokens[] =
9768 {
9769   {
9770     TYPE_KEY_X11,
9771     &setup.shortcut.save_game,                  "shortcut.save_game"
9772   },
9773   {
9774     TYPE_KEY_X11,
9775     &setup.shortcut.load_game,                  "shortcut.load_game"
9776   },
9777   {
9778     TYPE_KEY_X11,
9779     &setup.shortcut.toggle_pause,               "shortcut.toggle_pause"
9780   },
9781   {
9782     TYPE_KEY_X11,
9783     &setup.shortcut.focus_player[0],            "shortcut.focus_player_1"
9784   },
9785   {
9786     TYPE_KEY_X11,
9787     &setup.shortcut.focus_player[1],            "shortcut.focus_player_2"
9788   },
9789   {
9790     TYPE_KEY_X11,
9791     &setup.shortcut.focus_player[2],            "shortcut.focus_player_3"
9792   },
9793   {
9794     TYPE_KEY_X11,
9795     &setup.shortcut.focus_player[3],            "shortcut.focus_player_4"
9796   },
9797   {
9798     TYPE_KEY_X11,
9799     &setup.shortcut.focus_player_all,           "shortcut.focus_player_all"
9800   },
9801   {
9802     TYPE_KEY_X11,
9803     &setup.shortcut.tape_eject,                 "shortcut.tape_eject"
9804   },
9805   {
9806     TYPE_KEY_X11,
9807     &setup.shortcut.tape_extra,                 "shortcut.tape_extra"
9808   },
9809   {
9810     TYPE_KEY_X11,
9811     &setup.shortcut.tape_stop,                  "shortcut.tape_stop"
9812   },
9813   {
9814     TYPE_KEY_X11,
9815     &setup.shortcut.tape_pause,                 "shortcut.tape_pause"
9816   },
9817   {
9818     TYPE_KEY_X11,
9819     &setup.shortcut.tape_record,                "shortcut.tape_record"
9820   },
9821   {
9822     TYPE_KEY_X11,
9823     &setup.shortcut.tape_play,                  "shortcut.tape_play"
9824   },
9825   {
9826     TYPE_KEY_X11,
9827     &setup.shortcut.sound_simple,               "shortcut.sound_simple"
9828   },
9829   {
9830     TYPE_KEY_X11,
9831     &setup.shortcut.sound_loops,                "shortcut.sound_loops"
9832   },
9833   {
9834     TYPE_KEY_X11,
9835     &setup.shortcut.sound_music,                "shortcut.sound_music"
9836   },
9837   {
9838     TYPE_KEY_X11,
9839     &setup.shortcut.snap_left,                  "shortcut.snap_left"
9840   },
9841   {
9842     TYPE_KEY_X11,
9843     &setup.shortcut.snap_right,                 "shortcut.snap_right"
9844   },
9845   {
9846     TYPE_KEY_X11,
9847     &setup.shortcut.snap_up,                    "shortcut.snap_up"
9848   },
9849   {
9850     TYPE_KEY_X11,
9851     &setup.shortcut.snap_down,                  "shortcut.snap_down"
9852   },
9853 };
9854
9855 static struct SetupInputInfo setup_input;
9856 static struct TokenInfo player_setup_tokens[] =
9857 {
9858   {
9859     TYPE_BOOLEAN,
9860     &setup_input.use_joystick,                  ".use_joystick"
9861   },
9862   {
9863     TYPE_STRING,
9864     &setup_input.joy.device_name,               ".joy.device_name"
9865   },
9866   {
9867     TYPE_INTEGER,
9868     &setup_input.joy.xleft,                     ".joy.xleft"
9869   },
9870   {
9871     TYPE_INTEGER,
9872     &setup_input.joy.xmiddle,                   ".joy.xmiddle"
9873   },
9874   {
9875     TYPE_INTEGER,
9876     &setup_input.joy.xright,                    ".joy.xright"
9877   },
9878   {
9879     TYPE_INTEGER,
9880     &setup_input.joy.yupper,                    ".joy.yupper"
9881   },
9882   {
9883     TYPE_INTEGER,
9884     &setup_input.joy.ymiddle,                   ".joy.ymiddle"
9885   },
9886   {
9887     TYPE_INTEGER,
9888     &setup_input.joy.ylower,                    ".joy.ylower"
9889   },
9890   {
9891     TYPE_INTEGER,
9892     &setup_input.joy.snap,                      ".joy.snap_field"
9893   },
9894   {
9895     TYPE_INTEGER,
9896     &setup_input.joy.drop,                      ".joy.place_bomb"
9897   },
9898   {
9899     TYPE_KEY_X11,
9900     &setup_input.key.left,                      ".key.move_left"
9901   },
9902   {
9903     TYPE_KEY_X11,
9904     &setup_input.key.right,                     ".key.move_right"
9905   },
9906   {
9907     TYPE_KEY_X11,
9908     &setup_input.key.up,                        ".key.move_up"
9909   },
9910   {
9911     TYPE_KEY_X11,
9912     &setup_input.key.down,                      ".key.move_down"
9913   },
9914   {
9915     TYPE_KEY_X11,
9916     &setup_input.key.snap,                      ".key.snap_field"
9917   },
9918   {
9919     TYPE_KEY_X11,
9920     &setup_input.key.drop,                      ".key.place_bomb"
9921   },
9922 };
9923
9924 static struct TokenInfo system_setup_tokens[] =
9925 {
9926   {
9927     TYPE_STRING,
9928     &setup.system.sdl_renderdriver,             "system.sdl_renderdriver"
9929   },
9930   {
9931     TYPE_STRING,
9932     &setup.system.sdl_videodriver,              "system.sdl_videodriver"
9933   },
9934   {
9935     TYPE_STRING,
9936     &setup.system.sdl_audiodriver,              "system.sdl_audiodriver"
9937   },
9938   {
9939     TYPE_INTEGER,
9940     &setup.system.audio_fragment_size,          "system.audio_fragment_size"
9941   },
9942 };
9943
9944 static struct TokenInfo internal_setup_tokens[] =
9945 {
9946   {
9947     TYPE_STRING,
9948     &setup.internal.program_title,              "program_title"
9949   },
9950   {
9951     TYPE_STRING,
9952     &setup.internal.program_version,            "program_version"
9953   },
9954   {
9955     TYPE_STRING,
9956     &setup.internal.program_author,             "program_author"
9957   },
9958   {
9959     TYPE_STRING,
9960     &setup.internal.program_email,              "program_email"
9961   },
9962   {
9963     TYPE_STRING,
9964     &setup.internal.program_website,            "program_website"
9965   },
9966   {
9967     TYPE_STRING,
9968     &setup.internal.program_copyright,          "program_copyright"
9969   },
9970   {
9971     TYPE_STRING,
9972     &setup.internal.program_company,            "program_company"
9973   },
9974   {
9975     TYPE_STRING,
9976     &setup.internal.program_icon_file,          "program_icon_file"
9977   },
9978   {
9979     TYPE_STRING,
9980     &setup.internal.default_graphics_set,       "default_graphics_set"
9981   },
9982   {
9983     TYPE_STRING,
9984     &setup.internal.default_sounds_set,         "default_sounds_set"
9985   },
9986   {
9987     TYPE_STRING,
9988     &setup.internal.default_music_set,          "default_music_set"
9989   },
9990   {
9991     TYPE_STRING,
9992     &setup.internal.fallback_graphics_file,     "fallback_graphics_file"
9993   },
9994   {
9995     TYPE_STRING,
9996     &setup.internal.fallback_sounds_file,       "fallback_sounds_file"
9997   },
9998   {
9999     TYPE_STRING,
10000     &setup.internal.fallback_music_file,        "fallback_music_file"
10001   },
10002   {
10003     TYPE_STRING,
10004     &setup.internal.default_level_series,       "default_level_series"
10005   },
10006   {
10007     TYPE_INTEGER,
10008     &setup.internal.default_window_width,       "default_window_width"
10009   },
10010   {
10011     TYPE_INTEGER,
10012     &setup.internal.default_window_height,      "default_window_height"
10013   },
10014   {
10015     TYPE_BOOLEAN,
10016     &setup.internal.choose_from_top_leveldir,   "choose_from_top_leveldir"
10017   },
10018   {
10019     TYPE_BOOLEAN,
10020     &setup.internal.show_scaling_in_title,      "show_scaling_in_title"
10021   },
10022   {
10023     TYPE_BOOLEAN,
10024     &setup.internal.create_user_levelset,       "create_user_levelset"
10025   },
10026   {
10027     TYPE_BOOLEAN,
10028     &setup.internal.menu_game,                  "menu_game"
10029   },
10030   {
10031     TYPE_BOOLEAN,
10032     &setup.internal.menu_editor,                "menu_editor"
10033   },
10034   {
10035     TYPE_BOOLEAN,
10036     &setup.internal.menu_graphics,              "menu_graphics"
10037   },
10038   {
10039     TYPE_BOOLEAN,
10040     &setup.internal.menu_sound,                 "menu_sound"
10041   },
10042   {
10043     TYPE_BOOLEAN,
10044     &setup.internal.menu_artwork,               "menu_artwork"
10045   },
10046   {
10047     TYPE_BOOLEAN,
10048     &setup.internal.menu_input,                 "menu_input"
10049   },
10050   {
10051     TYPE_BOOLEAN,
10052     &setup.internal.menu_touch,                 "menu_touch"
10053   },
10054   {
10055     TYPE_BOOLEAN,
10056     &setup.internal.menu_shortcuts,             "menu_shortcuts"
10057   },
10058   {
10059     TYPE_BOOLEAN,
10060     &setup.internal.menu_exit,                  "menu_exit"
10061   },
10062   {
10063     TYPE_BOOLEAN,
10064     &setup.internal.menu_save_and_exit,         "menu_save_and_exit"
10065   },
10066 };
10067
10068 static struct TokenInfo debug_setup_tokens[] =
10069 {
10070   {
10071     TYPE_INTEGER,
10072     &setup.debug.frame_delay[0],                "debug.frame_delay_0"
10073   },
10074   {
10075     TYPE_INTEGER,
10076     &setup.debug.frame_delay[1],                "debug.frame_delay_1"
10077   },
10078   {
10079     TYPE_INTEGER,
10080     &setup.debug.frame_delay[2],                "debug.frame_delay_2"
10081   },
10082   {
10083     TYPE_INTEGER,
10084     &setup.debug.frame_delay[3],                "debug.frame_delay_3"
10085   },
10086   {
10087     TYPE_INTEGER,
10088     &setup.debug.frame_delay[4],                "debug.frame_delay_4"
10089   },
10090   {
10091     TYPE_INTEGER,
10092     &setup.debug.frame_delay[5],                "debug.frame_delay_5"
10093   },
10094   {
10095     TYPE_INTEGER,
10096     &setup.debug.frame_delay[6],                "debug.frame_delay_6"
10097   },
10098   {
10099     TYPE_INTEGER,
10100     &setup.debug.frame_delay[7],                "debug.frame_delay_7"
10101   },
10102   {
10103     TYPE_INTEGER,
10104     &setup.debug.frame_delay[8],                "debug.frame_delay_8"
10105   },
10106   {
10107     TYPE_INTEGER,
10108     &setup.debug.frame_delay[9],                "debug.frame_delay_9"
10109   },
10110   {
10111     TYPE_KEY_X11,
10112     &setup.debug.frame_delay_key[0],            "debug.key.frame_delay_0"
10113   },
10114   {
10115     TYPE_KEY_X11,
10116     &setup.debug.frame_delay_key[1],            "debug.key.frame_delay_1"
10117   },
10118   {
10119     TYPE_KEY_X11,
10120     &setup.debug.frame_delay_key[2],            "debug.key.frame_delay_2"
10121   },
10122   {
10123     TYPE_KEY_X11,
10124     &setup.debug.frame_delay_key[3],            "debug.key.frame_delay_3"
10125   },
10126   {
10127     TYPE_KEY_X11,
10128     &setup.debug.frame_delay_key[4],            "debug.key.frame_delay_4"
10129   },
10130   {
10131     TYPE_KEY_X11,
10132     &setup.debug.frame_delay_key[5],            "debug.key.frame_delay_5"
10133   },
10134   {
10135     TYPE_KEY_X11,
10136     &setup.debug.frame_delay_key[6],            "debug.key.frame_delay_6"
10137   },
10138   {
10139     TYPE_KEY_X11,
10140     &setup.debug.frame_delay_key[7],            "debug.key.frame_delay_7"
10141   },
10142   {
10143     TYPE_KEY_X11,
10144     &setup.debug.frame_delay_key[8],            "debug.key.frame_delay_8"
10145   },
10146   {
10147     TYPE_KEY_X11,
10148     &setup.debug.frame_delay_key[9],            "debug.key.frame_delay_9"
10149   },
10150   {
10151     TYPE_BOOLEAN,
10152     &setup.debug.frame_delay_use_mod_key,       "debug.frame_delay.use_mod_key"},
10153   {
10154     TYPE_BOOLEAN,
10155     &setup.debug.frame_delay_game_only,         "debug.frame_delay.game_only"
10156   },
10157   {
10158     TYPE_BOOLEAN,
10159     &setup.debug.show_frames_per_second,        "debug.show_frames_per_second"
10160   },
10161   {
10162     TYPE_SWITCH3,
10163     &setup.debug.xsn_mode,                      "debug.xsn_mode"
10164   },
10165   {
10166     TYPE_INTEGER,
10167     &setup.debug.xsn_percent,                   "debug.xsn_percent"
10168   },
10169 };
10170
10171 static struct TokenInfo options_setup_tokens[] =
10172 {
10173   {
10174     TYPE_BOOLEAN,
10175     &setup.options.verbose,                     "options.verbose"
10176   },
10177 };
10178
10179 static void setSetupInfoToDefaults(struct SetupInfo *si)
10180 {
10181   int i;
10182
10183   si->player_name = getStringCopy(getDefaultUserName(user.nr));
10184
10185   si->multiple_users = TRUE;
10186
10187   si->sound = TRUE;
10188   si->sound_loops = TRUE;
10189   si->sound_music = TRUE;
10190   si->sound_simple = TRUE;
10191   si->toons = TRUE;
10192   si->scroll_delay = TRUE;
10193   si->forced_scroll_delay = FALSE;
10194   si->scroll_delay_value = STD_SCROLL_DELAY;
10195   si->engine_snapshot_mode = getStringCopy(STR_SNAPSHOT_MODE_DEFAULT);
10196   si->engine_snapshot_memory = SNAPSHOT_MEMORY_DEFAULT;
10197   si->fade_screens = TRUE;
10198   si->autorecord = TRUE;
10199   si->show_titlescreen = TRUE;
10200   si->quick_doors = FALSE;
10201   si->team_mode = FALSE;
10202   si->handicap = TRUE;
10203   si->skip_levels = TRUE;
10204   si->increment_levels = TRUE;
10205   si->auto_play_next_level = TRUE;
10206   si->count_score_after_game = TRUE;
10207   si->show_scores_after_game = TRUE;
10208   si->time_limit = TRUE;
10209   si->fullscreen = FALSE;
10210   si->window_scaling_percent = STD_WINDOW_SCALING_PERCENT;
10211   si->window_scaling_quality = getStringCopy(SCALING_QUALITY_DEFAULT);
10212   si->screen_rendering_mode = getStringCopy(STR_SPECIAL_RENDERING_DEFAULT);
10213   si->vsync_mode = getStringCopy(STR_VSYNC_MODE_DEFAULT);
10214   si->ask_on_escape = TRUE;
10215   si->ask_on_escape_editor = TRUE;
10216   si->ask_on_game_over = TRUE;
10217   si->ask_on_quit_game = TRUE;
10218   si->ask_on_quit_program = TRUE;
10219   si->quick_switch = FALSE;
10220   si->input_on_focus = FALSE;
10221   si->prefer_aga_graphics = TRUE;
10222   si->prefer_lowpass_sounds = FALSE;
10223   si->prefer_extra_panel_items = TRUE;
10224   si->game_speed_extended = FALSE;
10225   si->game_frame_delay = GAME_FRAME_DELAY;
10226   si->sp_show_border_elements = FALSE;
10227   si->small_game_graphics = FALSE;
10228   si->show_snapshot_buttons = FALSE;
10229   si->only_show_local_scores = FALSE;
10230
10231   si->graphics_set = getStringCopy(GFX_CLASSIC_SUBDIR);
10232   si->sounds_set   = getStringCopy(SND_CLASSIC_SUBDIR);
10233   si->music_set    = getStringCopy(MUS_CLASSIC_SUBDIR);
10234
10235   si->override_level_graphics = FALSE;
10236   si->override_level_sounds = FALSE;
10237   si->override_level_music = FALSE;
10238
10239   si->volume_simple = 100;              // percent
10240   si->volume_loops = 100;               // percent
10241   si->volume_music = 100;               // percent
10242
10243   si->network_mode = FALSE;
10244   si->network_player_nr = 0;            // first player
10245   si->network_server_hostname = getStringCopy(STR_NETWORK_AUTO_DETECT);
10246
10247   si->api_server = TRUE;
10248   si->api_server_hostname = getStringCopy(API_SERVER_HOSTNAME);
10249
10250   si->touch.control_type = getStringCopy(TOUCH_CONTROL_DEFAULT);
10251   si->touch.move_distance = TOUCH_MOVE_DISTANCE_DEFAULT;        // percent
10252   si->touch.drop_distance = TOUCH_DROP_DISTANCE_DEFAULT;        // percent
10253   si->touch.transparency = TOUCH_TRANSPARENCY_DEFAULT;          // percent
10254   si->touch.draw_outlined = TRUE;
10255   si->touch.draw_pressed = TRUE;
10256
10257   for (i = 0; i < 2; i++)
10258   {
10259     char *default_grid_button[6][2] =
10260     {
10261       { "      ", "  ^^  " },
10262       { "      ", "  ^^  " },
10263       { "      ", "<<  >>" },
10264       { "      ", "<<  >>" },
10265       { "111222", "  vv  " },
10266       { "111222", "  vv  " }
10267     };
10268     int grid_xsize = DEFAULT_GRID_XSIZE(i);
10269     int grid_ysize = DEFAULT_GRID_YSIZE(i);
10270     int min_xsize = MIN(6, grid_xsize);
10271     int min_ysize = MIN(6, grid_ysize);
10272     int startx = grid_xsize - min_xsize;
10273     int starty = grid_ysize - min_ysize;
10274     int x, y;
10275
10276     // virtual buttons grid can only be set to defaults if video is initialized
10277     // (this will be repeated if virtual buttons are not loaded from setup file)
10278     if (video.initialized)
10279     {
10280       si->touch.grid_xsize[i] = grid_xsize;
10281       si->touch.grid_ysize[i] = grid_ysize;
10282     }
10283     else
10284     {
10285       si->touch.grid_xsize[i] = -1;
10286       si->touch.grid_ysize[i] = -1;
10287     }
10288
10289     for (x = 0; x < MAX_GRID_XSIZE; x++)
10290       for (y = 0; y < MAX_GRID_YSIZE; y++)
10291         si->touch.grid_button[i][x][y] = CHAR_GRID_BUTTON_NONE;
10292
10293     for (x = 0; x < min_xsize; x++)
10294       for (y = 0; y < min_ysize; y++)
10295         si->touch.grid_button[i][x][starty + y] =
10296           default_grid_button[y][0][x];
10297
10298     for (x = 0; x < min_xsize; x++)
10299       for (y = 0; y < min_ysize; y++)
10300         si->touch.grid_button[i][startx + x][starty + y] =
10301           default_grid_button[y][1][x];
10302   }
10303
10304   si->touch.grid_initialized            = video.initialized;
10305
10306   si->editor.el_boulderdash             = TRUE;
10307   si->editor.el_emerald_mine            = TRUE;
10308   si->editor.el_emerald_mine_club       = TRUE;
10309   si->editor.el_more                    = TRUE;
10310   si->editor.el_sokoban                 = TRUE;
10311   si->editor.el_supaplex                = TRUE;
10312   si->editor.el_diamond_caves           = TRUE;
10313   si->editor.el_dx_boulderdash          = TRUE;
10314
10315   si->editor.el_mirror_magic            = TRUE;
10316   si->editor.el_deflektor               = TRUE;
10317
10318   si->editor.el_chars                   = TRUE;
10319   si->editor.el_steel_chars             = TRUE;
10320
10321   si->editor.el_classic                 = TRUE;
10322   si->editor.el_custom                  = TRUE;
10323
10324   si->editor.el_user_defined            = FALSE;
10325   si->editor.el_dynamic                 = TRUE;
10326
10327   si->editor.el_headlines               = TRUE;
10328
10329   si->editor.show_element_token         = FALSE;
10330
10331   si->editor.show_read_only_warning     = TRUE;
10332
10333   si->editor.use_template_for_new_levels = TRUE;
10334
10335   si->shortcut.save_game        = DEFAULT_KEY_SAVE_GAME;
10336   si->shortcut.load_game        = DEFAULT_KEY_LOAD_GAME;
10337   si->shortcut.toggle_pause     = DEFAULT_KEY_TOGGLE_PAUSE;
10338
10339   si->shortcut.focus_player[0]  = DEFAULT_KEY_FOCUS_PLAYER_1;
10340   si->shortcut.focus_player[1]  = DEFAULT_KEY_FOCUS_PLAYER_2;
10341   si->shortcut.focus_player[2]  = DEFAULT_KEY_FOCUS_PLAYER_3;
10342   si->shortcut.focus_player[3]  = DEFAULT_KEY_FOCUS_PLAYER_4;
10343   si->shortcut.focus_player_all = DEFAULT_KEY_FOCUS_PLAYER_ALL;
10344
10345   si->shortcut.tape_eject       = DEFAULT_KEY_TAPE_EJECT;
10346   si->shortcut.tape_extra       = DEFAULT_KEY_TAPE_EXTRA;
10347   si->shortcut.tape_stop        = DEFAULT_KEY_TAPE_STOP;
10348   si->shortcut.tape_pause       = DEFAULT_KEY_TAPE_PAUSE;
10349   si->shortcut.tape_record      = DEFAULT_KEY_TAPE_RECORD;
10350   si->shortcut.tape_play        = DEFAULT_KEY_TAPE_PLAY;
10351
10352   si->shortcut.sound_simple     = DEFAULT_KEY_SOUND_SIMPLE;
10353   si->shortcut.sound_loops      = DEFAULT_KEY_SOUND_LOOPS;
10354   si->shortcut.sound_music      = DEFAULT_KEY_SOUND_MUSIC;
10355
10356   si->shortcut.snap_left        = DEFAULT_KEY_SNAP_LEFT;
10357   si->shortcut.snap_right       = DEFAULT_KEY_SNAP_RIGHT;
10358   si->shortcut.snap_up          = DEFAULT_KEY_SNAP_UP;
10359   si->shortcut.snap_down        = DEFAULT_KEY_SNAP_DOWN;
10360
10361   for (i = 0; i < MAX_PLAYERS; i++)
10362   {
10363     si->input[i].use_joystick = FALSE;
10364     si->input[i].joy.device_name=getStringCopy(getDeviceNameFromJoystickNr(i));
10365     si->input[i].joy.xleft   = JOYSTICK_XLEFT;
10366     si->input[i].joy.xmiddle = JOYSTICK_XMIDDLE;
10367     si->input[i].joy.xright  = JOYSTICK_XRIGHT;
10368     si->input[i].joy.yupper  = JOYSTICK_YUPPER;
10369     si->input[i].joy.ymiddle = JOYSTICK_YMIDDLE;
10370     si->input[i].joy.ylower  = JOYSTICK_YLOWER;
10371     si->input[i].joy.snap  = (i == 0 ? JOY_BUTTON_1 : 0);
10372     si->input[i].joy.drop  = (i == 0 ? JOY_BUTTON_2 : 0);
10373     si->input[i].key.left  = (i == 0 ? DEFAULT_KEY_LEFT  : KSYM_UNDEFINED);
10374     si->input[i].key.right = (i == 0 ? DEFAULT_KEY_RIGHT : KSYM_UNDEFINED);
10375     si->input[i].key.up    = (i == 0 ? DEFAULT_KEY_UP    : KSYM_UNDEFINED);
10376     si->input[i].key.down  = (i == 0 ? DEFAULT_KEY_DOWN  : KSYM_UNDEFINED);
10377     si->input[i].key.snap  = (i == 0 ? DEFAULT_KEY_SNAP  : KSYM_UNDEFINED);
10378     si->input[i].key.drop  = (i == 0 ? DEFAULT_KEY_DROP  : KSYM_UNDEFINED);
10379   }
10380
10381   si->system.sdl_renderdriver = getStringCopy(ARG_DEFAULT);
10382   si->system.sdl_videodriver = getStringCopy(ARG_DEFAULT);
10383   si->system.sdl_audiodriver = getStringCopy(ARG_DEFAULT);
10384   si->system.audio_fragment_size = DEFAULT_AUDIO_FRAGMENT_SIZE;
10385
10386   si->internal.program_title     = getStringCopy(PROGRAM_TITLE_STRING);
10387   si->internal.program_version   = getStringCopy(getProgramRealVersionString());
10388   si->internal.program_author    = getStringCopy(PROGRAM_AUTHOR_STRING);
10389   si->internal.program_email     = getStringCopy(PROGRAM_EMAIL_STRING);
10390   si->internal.program_website   = getStringCopy(PROGRAM_WEBSITE_STRING);
10391   si->internal.program_copyright = getStringCopy(PROGRAM_COPYRIGHT_STRING);
10392   si->internal.program_company   = getStringCopy(PROGRAM_COMPANY_STRING);
10393
10394   si->internal.program_icon_file = getStringCopy(PROGRAM_ICON_FILENAME);
10395
10396   si->internal.default_graphics_set = getStringCopy(GFX_CLASSIC_SUBDIR);
10397   si->internal.default_sounds_set   = getStringCopy(SND_CLASSIC_SUBDIR);
10398   si->internal.default_music_set    = getStringCopy(MUS_CLASSIC_SUBDIR);
10399
10400   si->internal.fallback_graphics_file = getStringCopy(UNDEFINED_FILENAME);
10401   si->internal.fallback_sounds_file   = getStringCopy(UNDEFINED_FILENAME);
10402   si->internal.fallback_music_file    = getStringCopy(UNDEFINED_FILENAME);
10403
10404   si->internal.default_level_series = getStringCopy(UNDEFINED_LEVELSET);
10405   si->internal.choose_from_top_leveldir = FALSE;
10406   si->internal.show_scaling_in_title = TRUE;
10407   si->internal.create_user_levelset = TRUE;
10408
10409   si->internal.default_window_width  = WIN_XSIZE_DEFAULT;
10410   si->internal.default_window_height = WIN_YSIZE_DEFAULT;
10411
10412   si->debug.frame_delay[0] = DEFAULT_FRAME_DELAY_0;
10413   si->debug.frame_delay[1] = DEFAULT_FRAME_DELAY_1;
10414   si->debug.frame_delay[2] = DEFAULT_FRAME_DELAY_2;
10415   si->debug.frame_delay[3] = DEFAULT_FRAME_DELAY_3;
10416   si->debug.frame_delay[4] = DEFAULT_FRAME_DELAY_4;
10417   si->debug.frame_delay[5] = DEFAULT_FRAME_DELAY_5;
10418   si->debug.frame_delay[6] = DEFAULT_FRAME_DELAY_6;
10419   si->debug.frame_delay[7] = DEFAULT_FRAME_DELAY_7;
10420   si->debug.frame_delay[8] = DEFAULT_FRAME_DELAY_8;
10421   si->debug.frame_delay[9] = DEFAULT_FRAME_DELAY_9;
10422
10423   si->debug.frame_delay_key[0] = DEFAULT_KEY_FRAME_DELAY_0;
10424   si->debug.frame_delay_key[1] = DEFAULT_KEY_FRAME_DELAY_1;
10425   si->debug.frame_delay_key[2] = DEFAULT_KEY_FRAME_DELAY_2;
10426   si->debug.frame_delay_key[3] = DEFAULT_KEY_FRAME_DELAY_3;
10427   si->debug.frame_delay_key[4] = DEFAULT_KEY_FRAME_DELAY_4;
10428   si->debug.frame_delay_key[5] = DEFAULT_KEY_FRAME_DELAY_5;
10429   si->debug.frame_delay_key[6] = DEFAULT_KEY_FRAME_DELAY_6;
10430   si->debug.frame_delay_key[7] = DEFAULT_KEY_FRAME_DELAY_7;
10431   si->debug.frame_delay_key[8] = DEFAULT_KEY_FRAME_DELAY_8;
10432   si->debug.frame_delay_key[9] = DEFAULT_KEY_FRAME_DELAY_9;
10433
10434   si->debug.frame_delay_use_mod_key = DEFAULT_FRAME_DELAY_USE_MOD_KEY;
10435   si->debug.frame_delay_game_only   = DEFAULT_FRAME_DELAY_GAME_ONLY;
10436
10437   si->debug.show_frames_per_second = FALSE;
10438
10439   si->debug.xsn_mode = AUTO;
10440   si->debug.xsn_percent = 0;
10441
10442   si->options.verbose = FALSE;
10443
10444 #if defined(PLATFORM_ANDROID)
10445   si->fullscreen = TRUE;
10446 #endif
10447
10448   setHideSetupEntry(&setup.debug.xsn_mode);
10449 }
10450
10451 static void setSetupInfoToDefaults_AutoSetup(struct SetupInfo *si)
10452 {
10453   si->auto_setup.editor_zoom_tilesize = MINI_TILESIZE;
10454 }
10455
10456 static void setSetupInfoToDefaults_EditorCascade(struct SetupInfo *si)
10457 {
10458   si->editor_cascade.el_bd              = TRUE;
10459   si->editor_cascade.el_em              = TRUE;
10460   si->editor_cascade.el_emc             = TRUE;
10461   si->editor_cascade.el_rnd             = TRUE;
10462   si->editor_cascade.el_sb              = TRUE;
10463   si->editor_cascade.el_sp              = TRUE;
10464   si->editor_cascade.el_dc              = TRUE;
10465   si->editor_cascade.el_dx              = TRUE;
10466
10467   si->editor_cascade.el_mm              = TRUE;
10468   si->editor_cascade.el_df              = TRUE;
10469
10470   si->editor_cascade.el_chars           = FALSE;
10471   si->editor_cascade.el_steel_chars     = FALSE;
10472   si->editor_cascade.el_ce              = FALSE;
10473   si->editor_cascade.el_ge              = FALSE;
10474   si->editor_cascade.el_ref             = FALSE;
10475   si->editor_cascade.el_user            = FALSE;
10476   si->editor_cascade.el_dynamic         = FALSE;
10477 }
10478
10479 #define MAX_HIDE_SETUP_TOKEN_SIZE               20
10480
10481 static char *getHideSetupToken(void *setup_value)
10482 {
10483   static char hide_setup_token[MAX_HIDE_SETUP_TOKEN_SIZE];
10484
10485   if (setup_value != NULL)
10486     snprintf(hide_setup_token, MAX_HIDE_SETUP_TOKEN_SIZE, "%p", setup_value);
10487
10488   return hide_setup_token;
10489 }
10490
10491 void setHideSetupEntry(void *setup_value)
10492 {
10493   char *hide_setup_token = getHideSetupToken(setup_value);
10494
10495   if (hide_setup_hash == NULL)
10496     hide_setup_hash = newSetupFileHash();
10497
10498   if (setup_value != NULL)
10499     setHashEntry(hide_setup_hash, hide_setup_token, "");
10500 }
10501
10502 void removeHideSetupEntry(void *setup_value)
10503 {
10504   char *hide_setup_token = getHideSetupToken(setup_value);
10505
10506   if (setup_value != NULL)
10507     removeHashEntry(hide_setup_hash, hide_setup_token);
10508 }
10509
10510 boolean hideSetupEntry(void *setup_value)
10511 {
10512   char *hide_setup_token = getHideSetupToken(setup_value);
10513
10514   return (setup_value != NULL &&
10515           getHashEntry(hide_setup_hash, hide_setup_token) != NULL);
10516 }
10517
10518 static void setSetupInfoFromTokenText(SetupFileHash *setup_file_hash,
10519                                       struct TokenInfo *token_info,
10520                                       int token_nr, char *token_text)
10521 {
10522   char *token_hide_text = getStringCat2(token_text, ".hide");
10523   char *token_hide_value = getHashEntry(setup_file_hash, token_hide_text);
10524
10525   // set the value of this setup option in the setup option structure
10526   setSetupInfo(token_info, token_nr, getHashEntry(setup_file_hash, token_text));
10527
10528   // check if this setup option should be hidden in the setup menu
10529   if (token_hide_value != NULL && get_boolean_from_string(token_hide_value))
10530     setHideSetupEntry(token_info[token_nr].value);
10531
10532   free(token_hide_text);
10533 }
10534
10535 static void setSetupInfoFromTokenInfo(SetupFileHash *setup_file_hash,
10536                                       struct TokenInfo *token_info,
10537                                       int token_nr)
10538 {
10539   setSetupInfoFromTokenText(setup_file_hash, token_info, token_nr,
10540                             token_info[token_nr].text);
10541 }
10542
10543 static void decodeSetupFileHash(SetupFileHash *setup_file_hash)
10544 {
10545   int i, pnr;
10546
10547   if (!setup_file_hash)
10548     return;
10549
10550   for (i = 0; i < ARRAY_SIZE(global_setup_tokens); i++)
10551     setSetupInfoFromTokenInfo(setup_file_hash, global_setup_tokens, i);
10552
10553   setup.touch.grid_initialized = TRUE;
10554   for (i = 0; i < 2; i++)
10555   {
10556     int grid_xsize = setup.touch.grid_xsize[i];
10557     int grid_ysize = setup.touch.grid_ysize[i];
10558     int x, y;
10559
10560     // if virtual buttons are not loaded from setup file, repeat initializing
10561     // virtual buttons grid with default values later when video is initialized
10562     if (grid_xsize == -1 ||
10563         grid_ysize == -1)
10564     {
10565       setup.touch.grid_initialized = FALSE;
10566
10567       continue;
10568     }
10569
10570     for (y = 0; y < grid_ysize; y++)
10571     {
10572       char token_string[MAX_LINE_LEN];
10573
10574       sprintf(token_string, "touch.virtual_buttons.%d.%02d", i, y);
10575
10576       char *value_string = getHashEntry(setup_file_hash, token_string);
10577
10578       if (value_string == NULL)
10579         continue;
10580
10581       for (x = 0; x < grid_xsize; x++)
10582       {
10583         char c = value_string[x];
10584
10585         setup.touch.grid_button[i][x][y] =
10586           (c == '.' ? CHAR_GRID_BUTTON_NONE : c);
10587       }
10588     }
10589   }
10590
10591   for (i = 0; i < ARRAY_SIZE(editor_setup_tokens); i++)
10592     setSetupInfoFromTokenInfo(setup_file_hash, editor_setup_tokens, i);
10593
10594   for (i = 0; i < ARRAY_SIZE(shortcut_setup_tokens); i++)
10595     setSetupInfoFromTokenInfo(setup_file_hash, shortcut_setup_tokens, i);
10596
10597   for (pnr = 0; pnr < MAX_PLAYERS; pnr++)
10598   {
10599     char prefix[30];
10600
10601     sprintf(prefix, "%s%d", TOKEN_STR_PLAYER_PREFIX, pnr + 1);
10602
10603     setup_input = setup.input[pnr];
10604     for (i = 0; i < ARRAY_SIZE(player_setup_tokens); i++)
10605     {
10606       char full_token[100];
10607
10608       sprintf(full_token, "%s%s", prefix, player_setup_tokens[i].text);
10609       setSetupInfoFromTokenText(setup_file_hash, player_setup_tokens, i,
10610                                 full_token);
10611     }
10612     setup.input[pnr] = setup_input;
10613   }
10614
10615   for (i = 0; i < ARRAY_SIZE(system_setup_tokens); i++)
10616     setSetupInfoFromTokenInfo(setup_file_hash, system_setup_tokens, i);
10617
10618   for (i = 0; i < ARRAY_SIZE(internal_setup_tokens); i++)
10619     setSetupInfoFromTokenInfo(setup_file_hash, internal_setup_tokens, i);
10620
10621   for (i = 0; i < ARRAY_SIZE(debug_setup_tokens); i++)
10622     setSetupInfoFromTokenInfo(setup_file_hash, debug_setup_tokens, i);
10623
10624   for (i = 0; i < ARRAY_SIZE(options_setup_tokens); i++)
10625     setSetupInfoFromTokenInfo(setup_file_hash, options_setup_tokens, i);
10626
10627   setHideRelatedSetupEntries();
10628 }
10629
10630 static void decodeSetupFileHash_AutoSetup(SetupFileHash *setup_file_hash)
10631 {
10632   int i;
10633
10634   if (!setup_file_hash)
10635     return;
10636
10637   for (i = 0; i < ARRAY_SIZE(auto_setup_tokens); i++)
10638     setSetupInfo(auto_setup_tokens, i,
10639                  getHashEntry(setup_file_hash,
10640                               auto_setup_tokens[i].text));
10641 }
10642
10643 static void decodeSetupFileHash_EditorCascade(SetupFileHash *setup_file_hash)
10644 {
10645   int i;
10646
10647   if (!setup_file_hash)
10648     return;
10649
10650   for (i = 0; i < ARRAY_SIZE(editor_cascade_setup_tokens); i++)
10651     setSetupInfo(editor_cascade_setup_tokens, i,
10652                  getHashEntry(setup_file_hash,
10653                               editor_cascade_setup_tokens[i].text));
10654 }
10655
10656 void LoadUserNames(void)
10657 {
10658   int last_user_nr = user.nr;
10659   int i;
10660
10661   if (global.user_names != NULL)
10662   {
10663     for (i = 0; i < MAX_PLAYER_NAMES; i++)
10664       checked_free(global.user_names[i]);
10665
10666     checked_free(global.user_names);
10667   }
10668
10669   global.user_names = checked_calloc(MAX_PLAYER_NAMES * sizeof(char *));
10670
10671   for (i = 0; i < MAX_PLAYER_NAMES; i++)
10672   {
10673     user.nr = i;
10674
10675     SetupFileHash *setup_file_hash = loadSetupFileHash(getSetupFilename());
10676
10677     if (setup_file_hash)
10678     {
10679       char *player_name = getHashEntry(setup_file_hash, "player_name");
10680
10681       global.user_names[i] = getFixedUserName(player_name);
10682
10683       freeSetupFileHash(setup_file_hash);
10684     }
10685
10686     if (global.user_names[i] == NULL)
10687       global.user_names[i] = getStringCopy(getDefaultUserName(i));
10688   }
10689
10690   user.nr = last_user_nr;
10691 }
10692
10693 void LoadSetupFromFilename(char *filename)
10694 {
10695   SetupFileHash *setup_file_hash = loadSetupFileHash(filename);
10696
10697   if (setup_file_hash)
10698   {
10699     decodeSetupFileHash(setup_file_hash);
10700
10701     freeSetupFileHash(setup_file_hash);
10702   }
10703   else
10704   {
10705     Debug("setup", "using default setup values");
10706   }
10707 }
10708
10709 static void LoadSetup_SpecialPostProcessing(void)
10710 {
10711   char *player_name_new;
10712
10713   // needed to work around problems with fixed length strings
10714   player_name_new = getFixedUserName(setup.player_name);
10715   free(setup.player_name);
10716   setup.player_name = player_name_new;
10717
10718   // "scroll_delay: on(3) / off(0)" was replaced by scroll delay value
10719   if (setup.scroll_delay == FALSE)
10720   {
10721     setup.scroll_delay_value = MIN_SCROLL_DELAY;
10722     setup.scroll_delay = TRUE;                  // now always "on"
10723   }
10724
10725   // make sure that scroll delay value stays inside valid range
10726   setup.scroll_delay_value =
10727     MIN(MAX(MIN_SCROLL_DELAY, setup.scroll_delay_value), MAX_SCROLL_DELAY);
10728 }
10729
10730 void LoadSetup(void)
10731 {
10732   char *filename;
10733
10734   // always start with reliable default values
10735   setSetupInfoToDefaults(&setup);
10736
10737   // try to load setup values from default setup file
10738   filename = getDefaultSetupFilename();
10739
10740   if (fileExists(filename))
10741     LoadSetupFromFilename(filename);
10742
10743   // try to load setup values from user setup file
10744   filename = getSetupFilename();
10745
10746   LoadSetupFromFilename(filename);
10747
10748   LoadSetup_SpecialPostProcessing();
10749 }
10750
10751 void LoadSetup_AutoSetup(void)
10752 {
10753   char *filename = getPath2(getSetupDir(), AUTOSETUP_FILENAME);
10754   SetupFileHash *setup_file_hash = NULL;
10755
10756   // always start with reliable default values
10757   setSetupInfoToDefaults_AutoSetup(&setup);
10758
10759   setup_file_hash = loadSetupFileHash(filename);
10760
10761   if (setup_file_hash)
10762   {
10763     decodeSetupFileHash_AutoSetup(setup_file_hash);
10764
10765     freeSetupFileHash(setup_file_hash);
10766   }
10767
10768   free(filename);
10769 }
10770
10771 void LoadSetup_EditorCascade(void)
10772 {
10773   char *filename = getPath2(getSetupDir(), EDITORCASCADE_FILENAME);
10774   SetupFileHash *setup_file_hash = NULL;
10775
10776   // always start with reliable default values
10777   setSetupInfoToDefaults_EditorCascade(&setup);
10778
10779   setup_file_hash = loadSetupFileHash(filename);
10780
10781   if (setup_file_hash)
10782   {
10783     decodeSetupFileHash_EditorCascade(setup_file_hash);
10784
10785     freeSetupFileHash(setup_file_hash);
10786   }
10787
10788   free(filename);
10789 }
10790
10791 static void addGameControllerMappingToHash(SetupFileHash *mappings_hash,
10792                                            char *mapping_line)
10793 {
10794   char mapping_guid[MAX_LINE_LEN];
10795   char *mapping_start, *mapping_end;
10796
10797   // get GUID from game controller mapping line: copy complete line
10798   strncpy(mapping_guid, mapping_line, MAX_LINE_LEN - 1);
10799   mapping_guid[MAX_LINE_LEN - 1] = '\0';
10800
10801   // get GUID from game controller mapping line: cut after GUID part
10802   mapping_start = strchr(mapping_guid, ',');
10803   if (mapping_start != NULL)
10804     *mapping_start = '\0';
10805
10806   // cut newline from game controller mapping line
10807   mapping_end = strchr(mapping_line, '\n');
10808   if (mapping_end != NULL)
10809     *mapping_end = '\0';
10810
10811   // add mapping entry to game controller mappings hash
10812   setHashEntry(mappings_hash, mapping_guid, mapping_line);
10813 }
10814
10815 static void LoadSetup_ReadGameControllerMappings(SetupFileHash *mappings_hash,
10816                                                  char *filename)
10817 {
10818   FILE *file;
10819
10820   if (!(file = fopen(filename, MODE_READ)))
10821   {
10822     Warn("cannot read game controller mappings file '%s'", filename);
10823
10824     return;
10825   }
10826
10827   while (!feof(file))
10828   {
10829     char line[MAX_LINE_LEN];
10830
10831     if (!fgets(line, MAX_LINE_LEN, file))
10832       break;
10833
10834     addGameControllerMappingToHash(mappings_hash, line);
10835   }
10836
10837   fclose(file);
10838 }
10839
10840 void SaveSetup(void)
10841 {
10842   char *filename = getSetupFilename();
10843   FILE *file;
10844   int i, pnr;
10845
10846   InitUserDataDirectory();
10847
10848   if (!(file = fopen(filename, MODE_WRITE)))
10849   {
10850     Warn("cannot write setup file '%s'", filename);
10851
10852     return;
10853   }
10854
10855   fprintFileHeader(file, SETUP_FILENAME);
10856
10857   for (i = 0; i < ARRAY_SIZE(global_setup_tokens); i++)
10858   {
10859     // just to make things nicer :)
10860     if (global_setup_tokens[i].value == &setup.multiple_users           ||
10861         global_setup_tokens[i].value == &setup.sound                    ||
10862         global_setup_tokens[i].value == &setup.graphics_set             ||
10863         global_setup_tokens[i].value == &setup.volume_simple            ||
10864         global_setup_tokens[i].value == &setup.network_mode             ||
10865         global_setup_tokens[i].value == &setup.api_server               ||
10866         global_setup_tokens[i].value == &setup.touch.control_type       ||
10867         global_setup_tokens[i].value == &setup.touch.grid_xsize[0]      ||
10868         global_setup_tokens[i].value == &setup.touch.grid_xsize[1])
10869       fprintf(file, "\n");
10870
10871     fprintf(file, "%s\n", getSetupLine(global_setup_tokens, "", i));
10872   }
10873
10874   for (i = 0; i < 2; i++)
10875   {
10876     int grid_xsize = setup.touch.grid_xsize[i];
10877     int grid_ysize = setup.touch.grid_ysize[i];
10878     int x, y;
10879
10880     fprintf(file, "\n");
10881
10882     for (y = 0; y < grid_ysize; y++)
10883     {
10884       char token_string[MAX_LINE_LEN];
10885       char value_string[MAX_LINE_LEN];
10886
10887       sprintf(token_string, "touch.virtual_buttons.%d.%02d", i, y);
10888
10889       for (x = 0; x < grid_xsize; x++)
10890       {
10891         char c = setup.touch.grid_button[i][x][y];
10892
10893         value_string[x] = (c == CHAR_GRID_BUTTON_NONE ? '.' : c);
10894       }
10895
10896       value_string[grid_xsize] = '\0';
10897
10898       fprintf(file, "%s\n", getFormattedSetupEntry(token_string, value_string));
10899     }
10900   }
10901
10902   fprintf(file, "\n");
10903   for (i = 0; i < ARRAY_SIZE(editor_setup_tokens); i++)
10904     fprintf(file, "%s\n", getSetupLine(editor_setup_tokens, "", i));
10905
10906   fprintf(file, "\n");
10907   for (i = 0; i < ARRAY_SIZE(shortcut_setup_tokens); i++)
10908     fprintf(file, "%s\n", getSetupLine(shortcut_setup_tokens, "", i));
10909
10910   for (pnr = 0; pnr < MAX_PLAYERS; pnr++)
10911   {
10912     char prefix[30];
10913
10914     sprintf(prefix, "%s%d", TOKEN_STR_PLAYER_PREFIX, pnr + 1);
10915     fprintf(file, "\n");
10916
10917     setup_input = setup.input[pnr];
10918     for (i = 0; i < ARRAY_SIZE(player_setup_tokens); i++)
10919       fprintf(file, "%s\n", getSetupLine(player_setup_tokens, prefix, i));
10920   }
10921
10922   fprintf(file, "\n");
10923   for (i = 0; i < ARRAY_SIZE(system_setup_tokens); i++)
10924     fprintf(file, "%s\n", getSetupLine(system_setup_tokens, "", i));
10925
10926   // (internal setup values not saved to user setup file)
10927
10928   fprintf(file, "\n");
10929   for (i = 0; i < ARRAY_SIZE(debug_setup_tokens); i++)
10930     if (!strPrefix(debug_setup_tokens[i].text, "debug.xsn_") ||
10931         setup.debug.xsn_mode != AUTO)
10932       fprintf(file, "%s\n", getSetupLine(debug_setup_tokens, "", i));
10933
10934   fprintf(file, "\n");
10935   for (i = 0; i < ARRAY_SIZE(options_setup_tokens); i++)
10936     fprintf(file, "%s\n", getSetupLine(options_setup_tokens, "", i));
10937
10938   fclose(file);
10939
10940   SetFilePermissions(filename, PERMS_PRIVATE);
10941 }
10942
10943 void SaveSetup_AutoSetup(void)
10944 {
10945   char *filename = getPath2(getSetupDir(), AUTOSETUP_FILENAME);
10946   FILE *file;
10947   int i;
10948
10949   InitUserDataDirectory();
10950
10951   if (!(file = fopen(filename, MODE_WRITE)))
10952   {
10953     Warn("cannot write auto setup file '%s'", filename);
10954
10955     free(filename);
10956
10957     return;
10958   }
10959
10960   fprintFileHeader(file, AUTOSETUP_FILENAME);
10961
10962   for (i = 0; i < ARRAY_SIZE(auto_setup_tokens); i++)
10963     fprintf(file, "%s\n", getSetupLine(auto_setup_tokens, "", i));
10964
10965   fclose(file);
10966
10967   SetFilePermissions(filename, PERMS_PRIVATE);
10968
10969   free(filename);
10970 }
10971
10972 void SaveSetup_EditorCascade(void)
10973 {
10974   char *filename = getPath2(getSetupDir(), EDITORCASCADE_FILENAME);
10975   FILE *file;
10976   int i;
10977
10978   InitUserDataDirectory();
10979
10980   if (!(file = fopen(filename, MODE_WRITE)))
10981   {
10982     Warn("cannot write editor cascade state file '%s'", filename);
10983
10984     free(filename);
10985
10986     return;
10987   }
10988
10989   fprintFileHeader(file, EDITORCASCADE_FILENAME);
10990
10991   for (i = 0; i < ARRAY_SIZE(editor_cascade_setup_tokens); i++)
10992     fprintf(file, "%s\n", getSetupLine(editor_cascade_setup_tokens, "", i));
10993
10994   fclose(file);
10995
10996   SetFilePermissions(filename, PERMS_PRIVATE);
10997
10998   free(filename);
10999 }
11000
11001 static void SaveSetup_WriteGameControllerMappings(SetupFileHash *mappings_hash,
11002                                                   char *filename)
11003 {
11004   FILE *file;
11005
11006   if (!(file = fopen(filename, MODE_WRITE)))
11007   {
11008     Warn("cannot write game controller mappings file '%s'", filename);
11009
11010     return;
11011   }
11012
11013   BEGIN_HASH_ITERATION(mappings_hash, itr)
11014   {
11015     fprintf(file, "%s\n", HASH_ITERATION_VALUE(itr));
11016   }
11017   END_HASH_ITERATION(mappings_hash, itr)
11018
11019   fclose(file);
11020 }
11021
11022 void SaveSetup_AddGameControllerMapping(char *mapping)
11023 {
11024   char *filename = getPath2(getSetupDir(), GAMECONTROLLER_BASENAME);
11025   SetupFileHash *mappings_hash = newSetupFileHash();
11026
11027   InitUserDataDirectory();
11028
11029   // load existing personal game controller mappings
11030   LoadSetup_ReadGameControllerMappings(mappings_hash, filename);
11031
11032   // add new mapping to personal game controller mappings
11033   addGameControllerMappingToHash(mappings_hash, mapping);
11034
11035   // save updated personal game controller mappings
11036   SaveSetup_WriteGameControllerMappings(mappings_hash, filename);
11037
11038   freeSetupFileHash(mappings_hash);
11039   free(filename);
11040 }
11041
11042 void LoadCustomElementDescriptions(void)
11043 {
11044   char *filename = getCustomArtworkConfigFilename(ARTWORK_TYPE_GRAPHICS);
11045   SetupFileHash *setup_file_hash;
11046   int i;
11047
11048   for (i = 0; i < NUM_FILE_ELEMENTS; i++)
11049   {
11050     if (element_info[i].custom_description != NULL)
11051     {
11052       free(element_info[i].custom_description);
11053       element_info[i].custom_description = NULL;
11054     }
11055   }
11056
11057   if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
11058     return;
11059
11060   for (i = 0; i < NUM_FILE_ELEMENTS; i++)
11061   {
11062     char *token = getStringCat2(element_info[i].token_name, ".name");
11063     char *value = getHashEntry(setup_file_hash, token);
11064
11065     if (value != NULL)
11066       element_info[i].custom_description = getStringCopy(value);
11067
11068     free(token);
11069   }
11070
11071   freeSetupFileHash(setup_file_hash);
11072 }
11073
11074 static int getElementFromToken(char *token)
11075 {
11076   char *value = getHashEntry(element_token_hash, token);
11077
11078   if (value != NULL)
11079     return atoi(value);
11080
11081   Warn("unknown element token '%s'", token);
11082
11083   return EL_UNDEFINED;
11084 }
11085
11086 void FreeGlobalAnimEventInfo(void)
11087 {
11088   struct GlobalAnimEventInfo *gaei = &global_anim_event_info;
11089
11090   if (gaei->event_list == NULL)
11091     return;
11092
11093   int i;
11094
11095   for (i = 0; i < gaei->num_event_lists; i++)
11096   {
11097     checked_free(gaei->event_list[i]->event_value);
11098     checked_free(gaei->event_list[i]);
11099   }
11100
11101   checked_free(gaei->event_list);
11102
11103   gaei->event_list = NULL;
11104   gaei->num_event_lists = 0;
11105 }
11106
11107 static int AddGlobalAnimEventList(void)
11108 {
11109   struct GlobalAnimEventInfo *gaei = &global_anim_event_info;
11110   int list_pos = gaei->num_event_lists++;
11111
11112   gaei->event_list = checked_realloc(gaei->event_list, gaei->num_event_lists *
11113                                      sizeof(struct GlobalAnimEventListInfo *));
11114
11115   gaei->event_list[list_pos] =
11116     checked_calloc(sizeof(struct GlobalAnimEventListInfo));
11117
11118   struct GlobalAnimEventListInfo *gaeli = gaei->event_list[list_pos];
11119
11120   gaeli->event_value = NULL;
11121   gaeli->num_event_values = 0;
11122
11123   return list_pos;
11124 }
11125
11126 static int AddGlobalAnimEventValue(int list_pos, int event_value)
11127 {
11128   // do not add empty global animation events
11129   if (event_value == ANIM_EVENT_NONE)
11130     return list_pos;
11131
11132   // if list position is undefined, create new list
11133   if (list_pos == ANIM_EVENT_UNDEFINED)
11134     list_pos = AddGlobalAnimEventList();
11135
11136   struct GlobalAnimEventInfo *gaei = &global_anim_event_info;
11137   struct GlobalAnimEventListInfo *gaeli = gaei->event_list[list_pos];
11138   int value_pos = gaeli->num_event_values++;
11139
11140   gaeli->event_value = checked_realloc(gaeli->event_value,
11141                                        gaeli->num_event_values * sizeof(int *));
11142
11143   gaeli->event_value[value_pos] = event_value;
11144
11145   return list_pos;
11146 }
11147
11148 int GetGlobalAnimEventValue(int list_pos, int value_pos)
11149 {
11150   if (list_pos == ANIM_EVENT_UNDEFINED)
11151     return ANIM_EVENT_NONE;
11152
11153   struct GlobalAnimEventInfo *gaei = &global_anim_event_info;
11154   struct GlobalAnimEventListInfo *gaeli = gaei->event_list[list_pos];
11155
11156   return gaeli->event_value[value_pos];
11157 }
11158
11159 int GetGlobalAnimEventValueCount(int list_pos)
11160 {
11161   if (list_pos == ANIM_EVENT_UNDEFINED)
11162     return 0;
11163
11164   struct GlobalAnimEventInfo *gaei = &global_anim_event_info;
11165   struct GlobalAnimEventListInfo *gaeli = gaei->event_list[list_pos];
11166
11167   return gaeli->num_event_values;
11168 }
11169
11170 // This function checks if a string <s> of the format "string1, string2, ..."
11171 // exactly contains a string <s_contained>.
11172
11173 static boolean string_has_parameter(char *s, char *s_contained)
11174 {
11175   char *substring;
11176
11177   if (s == NULL || s_contained == NULL)
11178     return FALSE;
11179
11180   if (strlen(s_contained) > strlen(s))
11181     return FALSE;
11182
11183   if (strncmp(s, s_contained, strlen(s_contained)) == 0)
11184   {
11185     char next_char = s[strlen(s_contained)];
11186
11187     // check if next character is delimiter or whitespace
11188     return (next_char == ',' || next_char == '\0' ||
11189             next_char == ' ' || next_char == '\t' ? TRUE : FALSE);
11190   }
11191
11192   // check if string contains another parameter string after a comma
11193   substring = strchr(s, ',');
11194   if (substring == NULL)        // string does not contain a comma
11195     return FALSE;
11196
11197   // advance string pointer to next character after the comma
11198   substring++;
11199
11200   // skip potential whitespaces after the comma
11201   while (*substring == ' ' || *substring == '\t')
11202     substring++;
11203
11204   return string_has_parameter(substring, s_contained);
11205 }
11206
11207 static int get_anim_parameter_value(char *s)
11208 {
11209   int event_value[] =
11210   {
11211     ANIM_EVENT_CLICK,
11212     ANIM_EVENT_INIT,
11213     ANIM_EVENT_START,
11214     ANIM_EVENT_END,
11215     ANIM_EVENT_POST
11216   };
11217   char *pattern_1[] =
11218   {
11219     "click:anim_",
11220     "init:anim_",
11221     "start:anim_",
11222     "end:anim_",
11223     "post:anim_"
11224   };
11225   char *pattern_2 = ".part_";
11226   char *matching_char = NULL;
11227   char *s_ptr = s;
11228   int pattern_1_len = 0;
11229   int result = ANIM_EVENT_NONE;
11230   int i;
11231
11232   for (i = 0; i < ARRAY_SIZE(event_value); i++)
11233   {
11234     matching_char = strstr(s_ptr, pattern_1[i]);
11235     pattern_1_len = strlen(pattern_1[i]);
11236     result = event_value[i];
11237
11238     if (matching_char != NULL)
11239       break;
11240   }
11241
11242   if (matching_char == NULL)
11243     return ANIM_EVENT_NONE;
11244
11245   s_ptr = matching_char + pattern_1_len;
11246
11247   // check for main animation number ("anim_X" or "anim_XX")
11248   if (*s_ptr >= '0' && *s_ptr <= '9')
11249   {
11250     int gic_anim_nr = (*s_ptr++ - '0');
11251
11252     if (*s_ptr >= '0' && *s_ptr <= '9')
11253       gic_anim_nr = 10 * gic_anim_nr + (*s_ptr++ - '0');
11254
11255     if (gic_anim_nr < 1 || gic_anim_nr > MAX_GLOBAL_ANIMS)
11256       return ANIM_EVENT_NONE;
11257
11258     result |= gic_anim_nr << ANIM_EVENT_ANIM_BIT;
11259   }
11260   else
11261   {
11262     // invalid main animation number specified
11263
11264     return ANIM_EVENT_NONE;
11265   }
11266
11267   // check for animation part number ("part_X" or "part_XX") (optional)
11268   if (strPrefix(s_ptr, pattern_2))
11269   {
11270     s_ptr += strlen(pattern_2);
11271
11272     if (*s_ptr >= '0' && *s_ptr <= '9')
11273     {
11274       int gic_part_nr = (*s_ptr++ - '0');
11275
11276       if (*s_ptr >= '0' && *s_ptr <= '9')
11277         gic_part_nr = 10 * gic_part_nr + (*s_ptr++ - '0');
11278
11279       if (gic_part_nr < 1 || gic_part_nr > MAX_GLOBAL_ANIM_PARTS)
11280         return ANIM_EVENT_NONE;
11281
11282       result |= gic_part_nr << ANIM_EVENT_PART_BIT;
11283     }
11284     else
11285     {
11286       // invalid animation part number specified
11287
11288       return ANIM_EVENT_NONE;
11289     }
11290   }
11291
11292   // discard result if next character is neither delimiter nor whitespace
11293   if (!(*s_ptr == ',' || *s_ptr == '\0' ||
11294         *s_ptr == ' ' || *s_ptr == '\t'))
11295     return ANIM_EVENT_NONE;
11296
11297   return result;
11298 }
11299
11300 static int get_anim_parameter_values(char *s)
11301 {
11302   int list_pos = ANIM_EVENT_UNDEFINED;
11303   int event_value = ANIM_EVENT_DEFAULT;
11304
11305   if (string_has_parameter(s, "any"))
11306     event_value |= ANIM_EVENT_ANY;
11307
11308   if (string_has_parameter(s, "click:self") ||
11309       string_has_parameter(s, "click") ||
11310       string_has_parameter(s, "self"))
11311     event_value |= ANIM_EVENT_SELF;
11312
11313   if (string_has_parameter(s, "unclick:any"))
11314     event_value |= ANIM_EVENT_UNCLICK_ANY;
11315
11316   // if animation event found, add it to global animation event list
11317   if (event_value != ANIM_EVENT_NONE)
11318     list_pos = AddGlobalAnimEventValue(list_pos, event_value);
11319
11320   while (s != NULL)
11321   {
11322     // add optional "click:anim_X" or "click:anim_X.part_X" parameter
11323     event_value = get_anim_parameter_value(s);
11324
11325     // if animation event found, add it to global animation event list
11326     if (event_value != ANIM_EVENT_NONE)
11327       list_pos = AddGlobalAnimEventValue(list_pos, event_value);
11328
11329     // continue with next part of the string, starting with next comma
11330     s = strchr(s + 1, ',');
11331   }
11332
11333   return list_pos;
11334 }
11335
11336 static int get_anim_action_parameter_value(char *token)
11337 {
11338   // check most common default case first to massively speed things up
11339   if (strEqual(token, ARG_UNDEFINED))
11340     return ANIM_EVENT_ACTION_NONE;
11341
11342   int result = getImageIDFromToken(token);
11343
11344   if (result == -1)
11345   {
11346     char *gfx_token = getStringCat2("gfx.", token);
11347
11348     result = getImageIDFromToken(gfx_token);
11349
11350     checked_free(gfx_token);
11351   }
11352
11353   if (result == -1)
11354   {
11355     Key key = getKeyFromX11KeyName(token);
11356
11357     if (key != KSYM_UNDEFINED)
11358       result = -(int)key;
11359   }
11360
11361   if (result == -1)
11362     result = ANIM_EVENT_ACTION_NONE;
11363
11364   return result;
11365 }
11366
11367 int get_parameter_value(char *value_raw, char *suffix, int type)
11368 {
11369   char *value = getStringToLower(value_raw);
11370   int result = 0;       // probably a save default value
11371
11372   if (strEqual(suffix, ".direction"))
11373   {
11374     result = (strEqual(value, "left")  ? MV_LEFT :
11375               strEqual(value, "right") ? MV_RIGHT :
11376               strEqual(value, "up")    ? MV_UP :
11377               strEqual(value, "down")  ? MV_DOWN : MV_NONE);
11378   }
11379   else if (strEqual(suffix, ".position"))
11380   {
11381     result = (strEqual(value, "left")   ? POS_LEFT :
11382               strEqual(value, "right")  ? POS_RIGHT :
11383               strEqual(value, "top")    ? POS_TOP :
11384               strEqual(value, "upper")  ? POS_UPPER :
11385               strEqual(value, "middle") ? POS_MIDDLE :
11386               strEqual(value, "lower")  ? POS_LOWER :
11387               strEqual(value, "bottom") ? POS_BOTTOM :
11388               strEqual(value, "any")    ? POS_ANY :
11389               strEqual(value, "last")   ? POS_LAST : POS_UNDEFINED);
11390   }
11391   else if (strEqual(suffix, ".align"))
11392   {
11393     result = (strEqual(value, "left")   ? ALIGN_LEFT :
11394               strEqual(value, "right")  ? ALIGN_RIGHT :
11395               strEqual(value, "center") ? ALIGN_CENTER :
11396               strEqual(value, "middle") ? ALIGN_CENTER : ALIGN_DEFAULT);
11397   }
11398   else if (strEqual(suffix, ".valign"))
11399   {
11400     result = (strEqual(value, "top")    ? VALIGN_TOP :
11401               strEqual(value, "bottom") ? VALIGN_BOTTOM :
11402               strEqual(value, "middle") ? VALIGN_MIDDLE :
11403               strEqual(value, "center") ? VALIGN_MIDDLE : VALIGN_DEFAULT);
11404   }
11405   else if (strEqual(suffix, ".anim_mode"))
11406   {
11407     result = (string_has_parameter(value, "none")       ? ANIM_NONE :
11408               string_has_parameter(value, "loop")       ? ANIM_LOOP :
11409               string_has_parameter(value, "linear")     ? ANIM_LINEAR :
11410               string_has_parameter(value, "pingpong")   ? ANIM_PINGPONG :
11411               string_has_parameter(value, "pingpong2")  ? ANIM_PINGPONG2 :
11412               string_has_parameter(value, "random")     ? ANIM_RANDOM :
11413               string_has_parameter(value, "ce_value")   ? ANIM_CE_VALUE :
11414               string_has_parameter(value, "ce_score")   ? ANIM_CE_SCORE :
11415               string_has_parameter(value, "ce_delay")   ? ANIM_CE_DELAY :
11416               string_has_parameter(value, "horizontal") ? ANIM_HORIZONTAL :
11417               string_has_parameter(value, "vertical")   ? ANIM_VERTICAL :
11418               string_has_parameter(value, "centered")   ? ANIM_CENTERED :
11419               string_has_parameter(value, "all")        ? ANIM_ALL :
11420               ANIM_DEFAULT);
11421
11422     if (string_has_parameter(value, "once"))
11423       result |= ANIM_ONCE;
11424
11425     if (string_has_parameter(value, "reverse"))
11426       result |= ANIM_REVERSE;
11427
11428     if (string_has_parameter(value, "opaque_player"))
11429       result |= ANIM_OPAQUE_PLAYER;
11430
11431     if (string_has_parameter(value, "static_panel"))
11432       result |= ANIM_STATIC_PANEL;
11433   }
11434   else if (strEqual(suffix, ".init_event") ||
11435            strEqual(suffix, ".anim_event"))
11436   {
11437     result = get_anim_parameter_values(value);
11438   }
11439   else if (strEqual(suffix, ".init_delay_action") ||
11440            strEqual(suffix, ".anim_delay_action") ||
11441            strEqual(suffix, ".post_delay_action") ||
11442            strEqual(suffix, ".init_event_action") ||
11443            strEqual(suffix, ".anim_event_action"))
11444   {
11445     result = get_anim_action_parameter_value(value_raw);
11446   }
11447   else if (strEqual(suffix, ".class"))
11448   {
11449     result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
11450               get_hash_from_key(value));
11451   }
11452   else if (strEqual(suffix, ".style"))
11453   {
11454     result = STYLE_DEFAULT;
11455
11456     if (string_has_parameter(value, "accurate_borders"))
11457       result |= STYLE_ACCURATE_BORDERS;
11458
11459     if (string_has_parameter(value, "inner_corners"))
11460       result |= STYLE_INNER_CORNERS;
11461
11462     if (string_has_parameter(value, "reverse"))
11463       result |= STYLE_REVERSE;
11464
11465     if (string_has_parameter(value, "leftmost_position"))
11466       result |= STYLE_LEFTMOST_POSITION;
11467
11468     if (string_has_parameter(value, "block_clicks"))
11469       result |= STYLE_BLOCK;
11470
11471     if (string_has_parameter(value, "passthrough_clicks"))
11472       result |= STYLE_PASSTHROUGH;
11473
11474     if (string_has_parameter(value, "multiple_actions"))
11475       result |= STYLE_MULTIPLE_ACTIONS;
11476   }
11477   else if (strEqual(suffix, ".fade_mode"))
11478   {
11479     result = (string_has_parameter(value, "none")       ? FADE_MODE_NONE :
11480               string_has_parameter(value, "fade")       ? FADE_MODE_FADE :
11481               string_has_parameter(value, "crossfade")  ? FADE_MODE_CROSSFADE :
11482               string_has_parameter(value, "melt")       ? FADE_MODE_MELT :
11483               string_has_parameter(value, "curtain")    ? FADE_MODE_CURTAIN :
11484               FADE_MODE_DEFAULT);
11485   }
11486   else if (strEqual(suffix, ".auto_delay_unit"))
11487   {
11488     result = (string_has_parameter(value, "ms")     ? AUTO_DELAY_UNIT_MS :
11489               string_has_parameter(value, "frames") ? AUTO_DELAY_UNIT_FRAMES :
11490               AUTO_DELAY_UNIT_DEFAULT);
11491   }
11492   else if (strPrefix(suffix, ".font"))          // (may also be ".font_xyz")
11493   {
11494     result = gfx.get_font_from_token_function(value);
11495   }
11496   else          // generic parameter of type integer or boolean
11497   {
11498     result = (strEqual(value, ARG_UNDEFINED) ? ARG_UNDEFINED_VALUE :
11499               type == TYPE_INTEGER ? get_integer_from_string(value) :
11500               type == TYPE_BOOLEAN ? get_boolean_from_string(value) :
11501               ARG_UNDEFINED_VALUE);
11502   }
11503
11504   free(value);
11505
11506   return result;
11507 }
11508
11509 static int get_token_parameter_value(char *token, char *value_raw)
11510 {
11511   char *suffix;
11512
11513   if (token == NULL || value_raw == NULL)
11514     return ARG_UNDEFINED_VALUE;
11515
11516   suffix = strrchr(token, '.');
11517   if (suffix == NULL)
11518     suffix = token;
11519
11520   if (strEqual(suffix, ".element"))
11521     return getElementFromToken(value_raw);
11522
11523   // !!! USE CORRECT VALUE TYPE (currently works also for TYPE_BOOLEAN) !!!
11524   return get_parameter_value(value_raw, suffix, TYPE_INTEGER);
11525 }
11526
11527 void InitMenuDesignSettings_Static(void)
11528 {
11529   int i;
11530
11531   // always start with reliable default values from static default config
11532   for (i = 0; image_config_vars[i].token != NULL; i++)
11533   {
11534     char *value = getHashEntry(image_config_hash, image_config_vars[i].token);
11535
11536     if (value != NULL)
11537       *image_config_vars[i].value =
11538         get_token_parameter_value(image_config_vars[i].token, value);
11539   }
11540 }
11541
11542 static void InitMenuDesignSettings_SpecialPreProcessing(void)
11543 {
11544   int i;
11545
11546   // the following initializes hierarchical values from static configuration
11547
11548   // special case: initialize "ARG_DEFAULT" values in static default config
11549   // (e.g., initialize "[titlemessage].fade_mode" from "[title].fade_mode")
11550   titlescreen_initial_first_default.fade_mode  =
11551     title_initial_first_default.fade_mode;
11552   titlescreen_initial_first_default.fade_delay =
11553     title_initial_first_default.fade_delay;
11554   titlescreen_initial_first_default.post_delay =
11555     title_initial_first_default.post_delay;
11556   titlescreen_initial_first_default.auto_delay =
11557     title_initial_first_default.auto_delay;
11558   titlescreen_initial_first_default.auto_delay_unit =
11559     title_initial_first_default.auto_delay_unit;
11560   titlescreen_first_default.fade_mode  = title_first_default.fade_mode;
11561   titlescreen_first_default.fade_delay = title_first_default.fade_delay;
11562   titlescreen_first_default.post_delay = title_first_default.post_delay;
11563   titlescreen_first_default.auto_delay = title_first_default.auto_delay;
11564   titlescreen_first_default.auto_delay_unit =
11565     title_first_default.auto_delay_unit;
11566   titlemessage_initial_first_default.fade_mode  =
11567     title_initial_first_default.fade_mode;
11568   titlemessage_initial_first_default.fade_delay =
11569     title_initial_first_default.fade_delay;
11570   titlemessage_initial_first_default.post_delay =
11571     title_initial_first_default.post_delay;
11572   titlemessage_initial_first_default.auto_delay =
11573     title_initial_first_default.auto_delay;
11574   titlemessage_initial_first_default.auto_delay_unit =
11575     title_initial_first_default.auto_delay_unit;
11576   titlemessage_first_default.fade_mode  = title_first_default.fade_mode;
11577   titlemessage_first_default.fade_delay = title_first_default.fade_delay;
11578   titlemessage_first_default.post_delay = title_first_default.post_delay;
11579   titlemessage_first_default.auto_delay = title_first_default.auto_delay;
11580   titlemessage_first_default.auto_delay_unit =
11581     title_first_default.auto_delay_unit;
11582
11583   titlescreen_initial_default.fade_mode  = title_initial_default.fade_mode;
11584   titlescreen_initial_default.fade_delay = title_initial_default.fade_delay;
11585   titlescreen_initial_default.post_delay = title_initial_default.post_delay;
11586   titlescreen_initial_default.auto_delay = title_initial_default.auto_delay;
11587   titlescreen_initial_default.auto_delay_unit =
11588     title_initial_default.auto_delay_unit;
11589   titlescreen_default.fade_mode  = title_default.fade_mode;
11590   titlescreen_default.fade_delay = title_default.fade_delay;
11591   titlescreen_default.post_delay = title_default.post_delay;
11592   titlescreen_default.auto_delay = title_default.auto_delay;
11593   titlescreen_default.auto_delay_unit = title_default.auto_delay_unit;
11594   titlemessage_initial_default.fade_mode  = title_initial_default.fade_mode;
11595   titlemessage_initial_default.fade_delay = title_initial_default.fade_delay;
11596   titlemessage_initial_default.post_delay = title_initial_default.post_delay;
11597   titlemessage_initial_default.auto_delay_unit =
11598     title_initial_default.auto_delay_unit;
11599   titlemessage_default.fade_mode  = title_default.fade_mode;
11600   titlemessage_default.fade_delay = title_default.fade_delay;
11601   titlemessage_default.post_delay = title_default.post_delay;
11602   titlemessage_default.auto_delay = title_default.auto_delay;
11603   titlemessage_default.auto_delay_unit = title_default.auto_delay_unit;
11604
11605   // special case: initialize "ARG_DEFAULT" values in static default config
11606   // (e.g., init "titlemessage_1.fade_mode" from "[titlemessage].fade_mode")
11607   for (i = 0; i < MAX_NUM_TITLE_MESSAGES; i++)
11608   {
11609     titlescreen_initial_first[i] = titlescreen_initial_first_default;
11610     titlescreen_first[i] = titlescreen_first_default;
11611     titlemessage_initial_first[i] = titlemessage_initial_first_default;
11612     titlemessage_first[i] = titlemessage_first_default;
11613
11614     titlescreen_initial[i] = titlescreen_initial_default;
11615     titlescreen[i] = titlescreen_default;
11616     titlemessage_initial[i] = titlemessage_initial_default;
11617     titlemessage[i] = titlemessage_default;
11618   }
11619
11620   // special case: initialize "ARG_DEFAULT" values in static default config
11621   // (eg, init "menu.enter_screen.SCORES.xyz" from "menu.enter_screen.xyz")
11622   for (i = 0; i < NUM_SPECIAL_GFX_ARGS; i++)
11623   {
11624     if (i == GFX_SPECIAL_ARG_TITLE)     // title values already initialized
11625       continue;
11626
11627     menu.enter_screen[i] = menu.enter_screen[GFX_SPECIAL_ARG_DEFAULT];
11628     menu.leave_screen[i] = menu.leave_screen[GFX_SPECIAL_ARG_DEFAULT];
11629     menu.next_screen[i]  = menu.next_screen[GFX_SPECIAL_ARG_DEFAULT];
11630   }
11631
11632   // special case: initialize "ARG_DEFAULT" values in static default config
11633   // (eg, init "viewport.door_1.MAIN.xyz" from "viewport.door_1.xyz")
11634   for (i = 0; i < NUM_SPECIAL_GFX_ARGS; i++)
11635   {
11636     viewport.window[i]    = viewport.window[GFX_SPECIAL_ARG_DEFAULT];
11637     viewport.playfield[i] = viewport.playfield[GFX_SPECIAL_ARG_DEFAULT];
11638     viewport.door_1[i]    = viewport.door_1[GFX_SPECIAL_ARG_DEFAULT];
11639
11640     if (i == GFX_SPECIAL_ARG_EDITOR)    // editor values already initialized
11641       continue;
11642
11643     viewport.door_2[i] = viewport.door_2[GFX_SPECIAL_ARG_DEFAULT];
11644   }
11645 }
11646
11647 static void InitMenuDesignSettings_SpecialPostProcessing(void)
11648 {
11649   static struct
11650   {
11651     struct XY *dst, *src;
11652   }
11653   game_buttons_xy[] =
11654   {
11655     { &game.button.save,        &game.button.stop       },
11656     { &game.button.pause2,      &game.button.pause      },
11657     { &game.button.load,        &game.button.play       },
11658     { &game.button.undo,        &game.button.stop       },
11659     { &game.button.redo,        &game.button.play       },
11660
11661     { NULL,                     NULL                    }
11662   };
11663   int i, j;
11664
11665   // special case: initialize later added SETUP list size from LEVELS value
11666   if (menu.list_size[GAME_MODE_SETUP] == -1)
11667     menu.list_size[GAME_MODE_SETUP] = menu.list_size[GAME_MODE_LEVELS];
11668
11669   // set default position for snapshot buttons to stop/pause/play buttons
11670   for (i = 0; game_buttons_xy[i].dst != NULL; i++)
11671     if ((*game_buttons_xy[i].dst).x == -1 &&
11672         (*game_buttons_xy[i].dst).y == -1)
11673       *game_buttons_xy[i].dst = *game_buttons_xy[i].src;
11674
11675   // --------------------------------------------------------------------------
11676   // dynamic viewports (including playfield margins, borders and alignments)
11677   // --------------------------------------------------------------------------
11678
11679   // dynamic viewports currently only supported for landscape mode
11680   int display_width  = MAX(video.display_width, video.display_height);
11681   int display_height = MIN(video.display_width, video.display_height);
11682
11683   for (i = 0; i < NUM_SPECIAL_GFX_ARGS; i++)
11684   {
11685     struct RectWithBorder *vp_window    = &viewport.window[i];
11686     struct RectWithBorder *vp_playfield = &viewport.playfield[i];
11687     struct RectWithBorder *vp_door_1    = &viewport.door_1[i];
11688     struct RectWithBorder *vp_door_2    = &viewport.door_2[i];
11689     boolean dynamic_window_width     = (vp_window->min_width     != -1);
11690     boolean dynamic_window_height    = (vp_window->min_height    != -1);
11691     boolean dynamic_playfield_width  = (vp_playfield->min_width  != -1);
11692     boolean dynamic_playfield_height = (vp_playfield->min_height != -1);
11693
11694     // adjust window size if min/max width/height is specified
11695
11696     if (vp_window->min_width != -1)
11697     {
11698       int window_width = display_width;
11699
11700       // when using static window height, use aspect ratio of display
11701       if (vp_window->min_height == -1)
11702         window_width = vp_window->height * display_width / display_height;
11703
11704       vp_window->width = MAX(vp_window->min_width, window_width);
11705     }
11706
11707     if (vp_window->min_height != -1)
11708     {
11709       int window_height = display_height;
11710
11711       // when using static window width, use aspect ratio of display
11712       if (vp_window->min_width == -1)
11713         window_height = vp_window->width * display_height / display_width;
11714
11715       vp_window->height = MAX(vp_window->min_height, window_height);
11716     }
11717
11718     if (vp_window->max_width != -1)
11719       vp_window->width = MIN(vp_window->width, vp_window->max_width);
11720
11721     if (vp_window->max_height != -1)
11722       vp_window->height = MIN(vp_window->height, vp_window->max_height);
11723
11724     int playfield_width  = vp_window->width;
11725     int playfield_height = vp_window->height;
11726
11727     // adjust playfield size and position according to specified margins
11728
11729     playfield_width  -= vp_playfield->margin_left;
11730     playfield_width  -= vp_playfield->margin_right;
11731
11732     playfield_height -= vp_playfield->margin_top;
11733     playfield_height -= vp_playfield->margin_bottom;
11734
11735     // adjust playfield size if min/max width/height is specified
11736
11737     if (vp_playfield->min_width != -1)
11738       vp_playfield->width = MAX(vp_playfield->min_width, playfield_width);
11739
11740     if (vp_playfield->min_height != -1)
11741       vp_playfield->height = MAX(vp_playfield->min_height, playfield_height);
11742
11743     if (vp_playfield->max_width != -1)
11744       vp_playfield->width = MIN(vp_playfield->width, vp_playfield->max_width);
11745
11746     if (vp_playfield->max_height != -1)
11747       vp_playfield->height = MIN(vp_playfield->height,vp_playfield->max_height);
11748
11749     // adjust playfield position according to specified alignment
11750
11751     if (vp_playfield->align == ALIGN_LEFT || vp_playfield->x > 0)
11752       vp_playfield->x = ALIGNED_VP_XPOS(vp_playfield);
11753     else if (vp_playfield->align == ALIGN_CENTER)
11754       vp_playfield->x = playfield_width / 2 - vp_playfield->width / 2;
11755     else if (vp_playfield->align == ALIGN_RIGHT)
11756       vp_playfield->x += playfield_width - vp_playfield->width;
11757
11758     if (vp_playfield->valign == VALIGN_TOP || vp_playfield->y > 0)
11759       vp_playfield->y = ALIGNED_VP_YPOS(vp_playfield);
11760     else if (vp_playfield->valign == VALIGN_MIDDLE)
11761       vp_playfield->y = playfield_height / 2 - vp_playfield->height / 2;
11762     else if (vp_playfield->valign == VALIGN_BOTTOM)
11763       vp_playfield->y += playfield_height - vp_playfield->height;
11764
11765     vp_playfield->x += vp_playfield->margin_left;
11766     vp_playfield->y += vp_playfield->margin_top;
11767
11768     // adjust individual playfield borders if only default border is specified
11769
11770     if (vp_playfield->border_left == -1)
11771       vp_playfield->border_left = vp_playfield->border_size;
11772     if (vp_playfield->border_right == -1)
11773       vp_playfield->border_right = vp_playfield->border_size;
11774     if (vp_playfield->border_top == -1)
11775       vp_playfield->border_top = vp_playfield->border_size;
11776     if (vp_playfield->border_bottom == -1)
11777       vp_playfield->border_bottom = vp_playfield->border_size;
11778
11779     // set dynamic playfield borders if borders are specified as undefined
11780     // (but only if window size was dynamic and playfield size was static)
11781
11782     if (dynamic_window_width && !dynamic_playfield_width)
11783     {
11784       if (vp_playfield->border_left == -1)
11785       {
11786         vp_playfield->border_left = (vp_playfield->x -
11787                                      vp_playfield->margin_left);
11788         vp_playfield->x     -= vp_playfield->border_left;
11789         vp_playfield->width += vp_playfield->border_left;
11790       }
11791
11792       if (vp_playfield->border_right == -1)
11793       {
11794         vp_playfield->border_right = (vp_window->width -
11795                                       vp_playfield->x -
11796                                       vp_playfield->width -
11797                                       vp_playfield->margin_right);
11798         vp_playfield->width += vp_playfield->border_right;
11799       }
11800     }
11801
11802     if (dynamic_window_height && !dynamic_playfield_height)
11803     {
11804       if (vp_playfield->border_top == -1)
11805       {
11806         vp_playfield->border_top = (vp_playfield->y -
11807                                     vp_playfield->margin_top);
11808         vp_playfield->y      -= vp_playfield->border_top;
11809         vp_playfield->height += vp_playfield->border_top;
11810       }
11811
11812       if (vp_playfield->border_bottom == -1)
11813       {
11814         vp_playfield->border_bottom = (vp_window->height -
11815                                        vp_playfield->y -
11816                                        vp_playfield->height -
11817                                        vp_playfield->margin_bottom);
11818         vp_playfield->height += vp_playfield->border_bottom;
11819       }
11820     }
11821
11822     // adjust playfield size to be a multiple of a defined alignment tile size
11823
11824     int align_size = vp_playfield->align_size;
11825     int playfield_xtiles = vp_playfield->width  / align_size;
11826     int playfield_ytiles = vp_playfield->height / align_size;
11827     int playfield_width_corrected  = playfield_xtiles * align_size;
11828     int playfield_height_corrected = playfield_ytiles * align_size;
11829     boolean is_playfield_mode = (i == GFX_SPECIAL_ARG_PLAYING ||
11830                                  i == GFX_SPECIAL_ARG_EDITOR);
11831
11832     if (is_playfield_mode &&
11833         dynamic_playfield_width &&
11834         vp_playfield->width != playfield_width_corrected)
11835     {
11836       int playfield_xdiff = vp_playfield->width - playfield_width_corrected;
11837
11838       vp_playfield->width = playfield_width_corrected;
11839
11840       if (vp_playfield->align == ALIGN_LEFT)
11841       {
11842         vp_playfield->border_left += playfield_xdiff;
11843       }
11844       else if (vp_playfield->align == ALIGN_RIGHT)
11845       {
11846         vp_playfield->border_right += playfield_xdiff;
11847       }
11848       else if (vp_playfield->align == ALIGN_CENTER)
11849       {
11850         int border_left_diff  = playfield_xdiff / 2;
11851         int border_right_diff = playfield_xdiff - border_left_diff;
11852
11853         vp_playfield->border_left  += border_left_diff;
11854         vp_playfield->border_right += border_right_diff;
11855       }
11856     }
11857
11858     if (is_playfield_mode &&
11859         dynamic_playfield_height &&
11860         vp_playfield->height != playfield_height_corrected)
11861     {
11862       int playfield_ydiff = vp_playfield->height - playfield_height_corrected;
11863
11864       vp_playfield->height = playfield_height_corrected;
11865
11866       if (vp_playfield->valign == VALIGN_TOP)
11867       {
11868         vp_playfield->border_top += playfield_ydiff;
11869       }
11870       else if (vp_playfield->align == VALIGN_BOTTOM)
11871       {
11872         vp_playfield->border_right += playfield_ydiff;
11873       }
11874       else if (vp_playfield->align == VALIGN_MIDDLE)
11875       {
11876         int border_top_diff    = playfield_ydiff / 2;
11877         int border_bottom_diff = playfield_ydiff - border_top_diff;
11878
11879         vp_playfield->border_top    += border_top_diff;
11880         vp_playfield->border_bottom += border_bottom_diff;
11881       }
11882     }
11883
11884     // adjust door positions according to specified alignment
11885
11886     for (j = 0; j < 2; j++)
11887     {
11888       struct RectWithBorder *vp_door = (j == 0 ? vp_door_1 : vp_door_2);
11889
11890       if (vp_door->align == ALIGN_LEFT || vp_door->x > 0)
11891         vp_door->x = ALIGNED_VP_XPOS(vp_door);
11892       else if (vp_door->align == ALIGN_CENTER)
11893         vp_door->x = vp_window->width / 2 - vp_door->width / 2;
11894       else if (vp_door->align == ALIGN_RIGHT)
11895         vp_door->x += vp_window->width - vp_door->width;
11896
11897       if (vp_door->valign == VALIGN_TOP || vp_door->y > 0)
11898         vp_door->y = ALIGNED_VP_YPOS(vp_door);
11899       else if (vp_door->valign == VALIGN_MIDDLE)
11900         vp_door->y = vp_window->height / 2 - vp_door->height / 2;
11901       else if (vp_door->valign == VALIGN_BOTTOM)
11902         vp_door->y += vp_window->height - vp_door->height;
11903     }
11904   }
11905 }
11906
11907 static void InitMenuDesignSettings_SpecialPostProcessing_AfterGraphics(void)
11908 {
11909   static struct
11910   {
11911     struct XYTileSize *dst, *src;
11912     int graphic;
11913   }
11914   editor_buttons_xy[] =
11915   {
11916     {
11917       &editor.button.element_left,      &editor.palette.element_left,
11918       IMG_GFX_EDITOR_BUTTON_ELEMENT_LEFT
11919     },
11920     {
11921       &editor.button.element_middle,    &editor.palette.element_middle,
11922       IMG_GFX_EDITOR_BUTTON_ELEMENT_MIDDLE
11923     },
11924     {
11925       &editor.button.element_right,     &editor.palette.element_right,
11926       IMG_GFX_EDITOR_BUTTON_ELEMENT_RIGHT
11927     },
11928
11929     { NULL,                     NULL                    }
11930   };
11931   int i;
11932
11933   // set default position for element buttons to element graphics
11934   for (i = 0; editor_buttons_xy[i].dst != NULL; i++)
11935   {
11936     if ((*editor_buttons_xy[i].dst).x == -1 &&
11937         (*editor_buttons_xy[i].dst).y == -1)
11938     {
11939       struct GraphicInfo *gd = &graphic_info[editor_buttons_xy[i].graphic];
11940
11941       gd->width = gd->height = editor_buttons_xy[i].src->tile_size;
11942
11943       *editor_buttons_xy[i].dst = *editor_buttons_xy[i].src;
11944     }
11945   }
11946
11947   // adjust editor palette rows and columns if specified to be dynamic
11948
11949   if (editor.palette.cols == -1)
11950   {
11951     int vp_width = viewport.playfield[GFX_SPECIAL_ARG_EDITOR].width;
11952     int bt_width = graphic_info[IMG_EDITOR_PALETTE_BUTTON].width;
11953     int sc_width = graphic_info[IMG_EDITOR_PALETTE_SCROLLBAR].width;
11954
11955     editor.palette.cols = (vp_width - sc_width) / bt_width;
11956
11957     if (editor.palette.x == -1)
11958     {
11959       int palette_width = editor.palette.cols * bt_width + sc_width;
11960
11961       editor.palette.x = (vp_width - palette_width) / 2;
11962     }
11963   }
11964
11965   if (editor.palette.rows == -1)
11966   {
11967     int vp_height = viewport.playfield[GFX_SPECIAL_ARG_EDITOR].height;
11968     int bt_height = graphic_info[IMG_EDITOR_PALETTE_BUTTON].height;
11969     int tx_height = getFontHeight(FONT_TEXT_2);
11970
11971     editor.palette.rows = (vp_height - tx_height) / bt_height;
11972
11973     if (editor.palette.y == -1)
11974     {
11975       int palette_height = editor.palette.rows * bt_height + tx_height;
11976
11977       editor.palette.y = (vp_height - palette_height) / 2;
11978     }
11979   }
11980 }
11981
11982 static void LoadMenuDesignSettingsFromFilename(char *filename)
11983 {
11984   static struct TitleFadingInfo tfi;
11985   static struct TitleMessageInfo tmi;
11986   static struct TokenInfo title_tokens[] =
11987   {
11988     { TYPE_INTEGER,     &tfi.fade_mode,         ".fade_mode"            },
11989     { TYPE_INTEGER,     &tfi.fade_delay,        ".fade_delay"           },
11990     { TYPE_INTEGER,     &tfi.post_delay,        ".post_delay"           },
11991     { TYPE_INTEGER,     &tfi.auto_delay,        ".auto_delay"           },
11992     { TYPE_INTEGER,     &tfi.auto_delay_unit,   ".auto_delay_unit"      },
11993
11994     { -1,               NULL,                   NULL                    }
11995   };
11996   static struct TokenInfo titlemessage_tokens[] =
11997   {
11998     { TYPE_INTEGER,     &tmi.x,                 ".x"                    },
11999     { TYPE_INTEGER,     &tmi.y,                 ".y"                    },
12000     { TYPE_INTEGER,     &tmi.width,             ".width"                },
12001     { TYPE_INTEGER,     &tmi.height,            ".height"               },
12002     { TYPE_INTEGER,     &tmi.chars,             ".chars"                },
12003     { TYPE_INTEGER,     &tmi.lines,             ".lines"                },
12004     { TYPE_INTEGER,     &tmi.align,             ".align"                },
12005     { TYPE_INTEGER,     &tmi.valign,            ".valign"               },
12006     { TYPE_INTEGER,     &tmi.font,              ".font"                 },
12007     { TYPE_BOOLEAN,     &tmi.autowrap,          ".autowrap"             },
12008     { TYPE_BOOLEAN,     &tmi.centered,          ".centered"             },
12009     { TYPE_BOOLEAN,     &tmi.parse_comments,    ".parse_comments"       },
12010     { TYPE_INTEGER,     &tmi.sort_priority,     ".sort_priority"        },
12011     { TYPE_INTEGER,     &tmi.fade_mode,         ".fade_mode"            },
12012     { TYPE_INTEGER,     &tmi.fade_delay,        ".fade_delay"           },
12013     { TYPE_INTEGER,     &tmi.post_delay,        ".post_delay"           },
12014     { TYPE_INTEGER,     &tmi.auto_delay,        ".auto_delay"           },
12015     { TYPE_INTEGER,     &tmi.auto_delay_unit,   ".auto_delay_unit"      },
12016
12017     { -1,               NULL,                   NULL                    }
12018   };
12019   static struct
12020   {
12021     struct TitleFadingInfo *info;
12022     char *text;
12023   }
12024   title_info[] =
12025   {
12026     // initialize first titles from "enter screen" definitions, if defined
12027     { &title_initial_first_default,     "menu.enter_screen.TITLE"       },
12028     { &title_first_default,             "menu.enter_screen.TITLE"       },
12029
12030     // initialize title screens from "next screen" definitions, if defined
12031     { &title_initial_default,           "menu.next_screen.TITLE"        },
12032     { &title_default,                   "menu.next_screen.TITLE"        },
12033
12034     { NULL,                             NULL                            }
12035   };
12036   static struct
12037   {
12038     struct TitleMessageInfo *array;
12039     char *text;
12040   }
12041   titlemessage_arrays[] =
12042   {
12043     // initialize first titles from "enter screen" definitions, if defined
12044     { titlescreen_initial_first,        "menu.enter_screen.TITLE"       },
12045     { titlescreen_first,                "menu.enter_screen.TITLE"       },
12046     { titlemessage_initial_first,       "menu.enter_screen.TITLE"       },
12047     { titlemessage_first,               "menu.enter_screen.TITLE"       },
12048
12049     // initialize titles from "next screen" definitions, if defined
12050     { titlescreen_initial,              "menu.next_screen.TITLE"        },
12051     { titlescreen,                      "menu.next_screen.TITLE"        },
12052     { titlemessage_initial,             "menu.next_screen.TITLE"        },
12053     { titlemessage,                     "menu.next_screen.TITLE"        },
12054
12055     // overwrite titles with title definitions, if defined
12056     { titlescreen_initial_first,        "[title_initial]"               },
12057     { titlescreen_first,                "[title]"                       },
12058     { titlemessage_initial_first,       "[title_initial]"               },
12059     { titlemessage_first,               "[title]"                       },
12060
12061     { titlescreen_initial,              "[title_initial]"               },
12062     { titlescreen,                      "[title]"                       },
12063     { titlemessage_initial,             "[title_initial]"               },
12064     { titlemessage,                     "[title]"                       },
12065
12066     // overwrite titles with title screen/message definitions, if defined
12067     { titlescreen_initial_first,        "[titlescreen_initial]"         },
12068     { titlescreen_first,                "[titlescreen]"                 },
12069     { titlemessage_initial_first,       "[titlemessage_initial]"        },
12070     { titlemessage_first,               "[titlemessage]"                },
12071
12072     { titlescreen_initial,              "[titlescreen_initial]"         },
12073     { titlescreen,                      "[titlescreen]"                 },
12074     { titlemessage_initial,             "[titlemessage_initial]"        },
12075     { titlemessage,                     "[titlemessage]"                },
12076
12077     { NULL,                             NULL                            }
12078   };
12079   SetupFileHash *setup_file_hash;
12080   int i, j, k;
12081
12082   if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
12083     return;
12084
12085   // the following initializes hierarchical values from dynamic configuration
12086
12087   // special case: initialize with default values that may be overwritten
12088   // (e.g., init "menu.draw_xoffset.INFO" from "menu.draw_xoffset")
12089   for (i = 0; i < NUM_SPECIAL_GFX_ARGS; i++)
12090   {
12091     struct TokenIntPtrInfo menu_config[] =
12092     {
12093       { "menu.draw_xoffset",    &menu.draw_xoffset[i]   },
12094       { "menu.draw_yoffset",    &menu.draw_yoffset[i]   },
12095       { "menu.list_size",       &menu.list_size[i]      }
12096     };
12097
12098     for (j = 0; j < ARRAY_SIZE(menu_config); j++)
12099     {
12100       char *token = menu_config[j].token;
12101       char *value = getHashEntry(setup_file_hash, token);
12102
12103       if (value != NULL)
12104         *menu_config[j].value = get_integer_from_string(value);
12105     }
12106   }
12107
12108   // special case: initialize with default values that may be overwritten
12109   // (eg, init "menu.draw_xoffset.INFO[XXX]" from "menu.draw_xoffset.INFO")
12110   for (i = 0; i < NUM_SPECIAL_GFX_INFO_ARGS; i++)
12111   {
12112     struct TokenIntPtrInfo menu_config[] =
12113     {
12114       { "menu.draw_xoffset.INFO",       &menu.draw_xoffset_info[i]      },
12115       { "menu.draw_yoffset.INFO",       &menu.draw_yoffset_info[i]      },
12116       { "menu.list_size.INFO",          &menu.list_size_info[i]         }
12117     };
12118
12119     for (j = 0; j < ARRAY_SIZE(menu_config); j++)
12120     {
12121       char *token = menu_config[j].token;
12122       char *value = getHashEntry(setup_file_hash, token);
12123
12124       if (value != NULL)
12125         *menu_config[j].value = get_integer_from_string(value);
12126     }
12127   }
12128
12129   // special case: initialize with default values that may be overwritten
12130   // (eg, init "menu.draw_xoffset.SETUP[XXX]" from "menu.draw_xoffset.SETUP")
12131   for (i = 0; i < NUM_SPECIAL_GFX_SETUP_ARGS; i++)
12132   {
12133     struct TokenIntPtrInfo menu_config[] =
12134     {
12135       { "menu.draw_xoffset.SETUP",      &menu.draw_xoffset_setup[i]     },
12136       { "menu.draw_yoffset.SETUP",      &menu.draw_yoffset_setup[i]     }
12137     };
12138
12139     for (j = 0; j < ARRAY_SIZE(menu_config); j++)
12140     {
12141       char *token = menu_config[j].token;
12142       char *value = getHashEntry(setup_file_hash, token);
12143
12144       if (value != NULL)
12145         *menu_config[j].value = get_integer_from_string(value);
12146     }
12147   }
12148
12149   // special case: initialize with default values that may be overwritten
12150   // (eg, init "menu.line_spacing.INFO[XXX]" from "menu.line_spacing.INFO")
12151   for (i = 0; i < NUM_SPECIAL_GFX_INFO_ARGS; i++)
12152   {
12153     struct TokenIntPtrInfo menu_config[] =
12154     {
12155       { "menu.left_spacing.INFO",       &menu.left_spacing_info[i]      },
12156       { "menu.right_spacing.INFO",      &menu.right_spacing_info[i]     },
12157       { "menu.top_spacing.INFO",        &menu.top_spacing_info[i]       },
12158       { "menu.bottom_spacing.INFO",     &menu.bottom_spacing_info[i]    },
12159       { "menu.paragraph_spacing.INFO",  &menu.paragraph_spacing_info[i] },
12160       { "menu.headline1_spacing.INFO",  &menu.headline1_spacing_info[i] },
12161       { "menu.headline2_spacing.INFO",  &menu.headline2_spacing_info[i] },
12162       { "menu.line_spacing.INFO",       &menu.line_spacing_info[i]      },
12163       { "menu.extra_spacing.INFO",      &menu.extra_spacing_info[i]     },
12164     };
12165
12166     for (j = 0; j < ARRAY_SIZE(menu_config); j++)
12167     {
12168       char *token = menu_config[j].token;
12169       char *value = getHashEntry(setup_file_hash, token);
12170
12171       if (value != NULL)
12172         *menu_config[j].value = get_integer_from_string(value);
12173     }
12174   }
12175
12176   // special case: initialize with default values that may be overwritten
12177   // (eg, init "menu.enter_screen.SCORES.xyz" from "menu.enter_screen.xyz")
12178   for (i = 0; i < NUM_SPECIAL_GFX_ARGS; i++)
12179   {
12180     struct TokenIntPtrInfo menu_config[] =
12181     {
12182       { "menu.enter_screen.fade_mode",  &menu.enter_screen[i].fade_mode  },
12183       { "menu.enter_screen.fade_delay", &menu.enter_screen[i].fade_delay },
12184       { "menu.enter_screen.post_delay", &menu.enter_screen[i].post_delay },
12185       { "menu.leave_screen.fade_mode",  &menu.leave_screen[i].fade_mode  },
12186       { "menu.leave_screen.fade_delay", &menu.leave_screen[i].fade_delay },
12187       { "menu.leave_screen.post_delay", &menu.leave_screen[i].post_delay },
12188       { "menu.next_screen.fade_mode",   &menu.next_screen[i].fade_mode   },
12189       { "menu.next_screen.fade_delay",  &menu.next_screen[i].fade_delay  },
12190       { "menu.next_screen.post_delay",  &menu.next_screen[i].post_delay  }
12191     };
12192
12193     for (j = 0; j < ARRAY_SIZE(menu_config); j++)
12194     {
12195       char *token = menu_config[j].token;
12196       char *value = getHashEntry(setup_file_hash, token);
12197
12198       if (value != NULL)
12199         *menu_config[j].value = get_token_parameter_value(token, value);
12200     }
12201   }
12202
12203   // special case: initialize with default values that may be overwritten
12204   // (eg, init "viewport.door_1.MAIN.xyz" from "viewport.door_1.xyz")
12205   for (i = 0; i < NUM_SPECIAL_GFX_ARGS; i++)
12206   {
12207     struct
12208     {
12209       char *token_prefix;
12210       struct RectWithBorder *struct_ptr;
12211     }
12212     vp_struct[] =
12213     {
12214       { "viewport.window",      &viewport.window[i]     },
12215       { "viewport.playfield",   &viewport.playfield[i]  },
12216       { "viewport.door_1",      &viewport.door_1[i]     },
12217       { "viewport.door_2",      &viewport.door_2[i]     }
12218     };
12219
12220     for (j = 0; j < ARRAY_SIZE(vp_struct); j++)
12221     {
12222       struct TokenIntPtrInfo vp_config[] =
12223       {
12224         { ".x",                 &vp_struct[j].struct_ptr->x             },
12225         { ".y",                 &vp_struct[j].struct_ptr->y             },
12226         { ".width",             &vp_struct[j].struct_ptr->width         },
12227         { ".height",            &vp_struct[j].struct_ptr->height        },
12228         { ".min_width",         &vp_struct[j].struct_ptr->min_width     },
12229         { ".min_height",        &vp_struct[j].struct_ptr->min_height    },
12230         { ".max_width",         &vp_struct[j].struct_ptr->max_width     },
12231         { ".max_height",        &vp_struct[j].struct_ptr->max_height    },
12232         { ".margin_left",       &vp_struct[j].struct_ptr->margin_left   },
12233         { ".margin_right",      &vp_struct[j].struct_ptr->margin_right  },
12234         { ".margin_top",        &vp_struct[j].struct_ptr->margin_top    },
12235         { ".margin_bottom",     &vp_struct[j].struct_ptr->margin_bottom },
12236         { ".border_left",       &vp_struct[j].struct_ptr->border_left   },
12237         { ".border_right",      &vp_struct[j].struct_ptr->border_right  },
12238         { ".border_top",        &vp_struct[j].struct_ptr->border_top    },
12239         { ".border_bottom",     &vp_struct[j].struct_ptr->border_bottom },
12240         { ".border_size",       &vp_struct[j].struct_ptr->border_size   },
12241         { ".align_size",        &vp_struct[j].struct_ptr->align_size    },
12242         { ".align",             &vp_struct[j].struct_ptr->align         },
12243         { ".valign",            &vp_struct[j].struct_ptr->valign        }
12244       };
12245
12246       for (k = 0; k < ARRAY_SIZE(vp_config); k++)
12247       {
12248         char *token = getStringCat2(vp_struct[j].token_prefix,
12249                                     vp_config[k].token);
12250         char *value = getHashEntry(setup_file_hash, token);
12251
12252         if (value != NULL)
12253           *vp_config[k].value = get_token_parameter_value(token, value);
12254
12255         free(token);
12256       }
12257     }
12258   }
12259
12260   // special case: initialize with default values that may be overwritten
12261   // (e.g., init "[title].fade_mode" from "menu.next_screen.TITLE.fade_mode")
12262   for (i = 0; title_info[i].info != NULL; i++)
12263   {
12264     struct TitleFadingInfo *info = title_info[i].info;
12265     char *base_token = title_info[i].text;
12266
12267     for (j = 0; title_tokens[j].type != -1; j++)
12268     {
12269       char *token = getStringCat2(base_token, title_tokens[j].text);
12270       char *value = getHashEntry(setup_file_hash, token);
12271
12272       if (value != NULL)
12273       {
12274         int parameter_value = get_token_parameter_value(token, value);
12275
12276         tfi = *info;
12277
12278         *(int *)title_tokens[j].value = (int)parameter_value;
12279
12280         *info = tfi;
12281       }
12282
12283       free(token);
12284     }
12285   }
12286
12287   // special case: initialize with default values that may be overwritten
12288   // (e.g., init "titlemessage_1.fade_mode" from "[titlemessage].fade_mode")
12289   for (i = 0; titlemessage_arrays[i].array != NULL; i++)
12290   {
12291     struct TitleMessageInfo *array = titlemessage_arrays[i].array;
12292     char *base_token = titlemessage_arrays[i].text;
12293
12294     for (j = 0; titlemessage_tokens[j].type != -1; j++)
12295     {
12296       char *token = getStringCat2(base_token, titlemessage_tokens[j].text);
12297       char *value = getHashEntry(setup_file_hash, token);
12298
12299       if (value != NULL)
12300       {
12301         int parameter_value = get_token_parameter_value(token, value);
12302
12303         for (k = 0; k < MAX_NUM_TITLE_MESSAGES; k++)
12304         {
12305           tmi = array[k];
12306
12307           if (titlemessage_tokens[j].type == TYPE_INTEGER)
12308             *(int     *)titlemessage_tokens[j].value = (int)parameter_value;
12309           else
12310             *(boolean *)titlemessage_tokens[j].value = (boolean)parameter_value;
12311
12312           array[k] = tmi;
12313         }
12314       }
12315
12316       free(token);
12317     }
12318   }
12319
12320   // special case: check if network and preview player positions are redefined,
12321   // to compare this later against the main menu level preview being redefined
12322   struct TokenIntPtrInfo menu_config_players[] =
12323   {
12324     { "main.network_players.x", &menu.main.network_players.redefined    },
12325     { "main.network_players.y", &menu.main.network_players.redefined    },
12326     { "main.preview_players.x", &menu.main.preview_players.redefined    },
12327     { "main.preview_players.y", &menu.main.preview_players.redefined    },
12328     { "preview.x",              &preview.redefined                      },
12329     { "preview.y",              &preview.redefined                      }
12330   };
12331
12332   for (i = 0; i < ARRAY_SIZE(menu_config_players); i++)
12333     *menu_config_players[i].value = FALSE;
12334
12335   for (i = 0; i < ARRAY_SIZE(menu_config_players); i++)
12336     if (getHashEntry(setup_file_hash, menu_config_players[i].token) != NULL)
12337       *menu_config_players[i].value = TRUE;
12338
12339   // read (and overwrite with) values that may be specified in config file
12340   for (i = 0; image_config_vars[i].token != NULL; i++)
12341   {
12342     char *value = getHashEntry(setup_file_hash, image_config_vars[i].token);
12343
12344     // (ignore definitions set to "[DEFAULT]" which are already initialized)
12345     if (value != NULL && !strEqual(value, ARG_DEFAULT))
12346       *image_config_vars[i].value =
12347         get_token_parameter_value(image_config_vars[i].token, value);
12348   }
12349
12350   freeSetupFileHash(setup_file_hash);
12351 }
12352
12353 void LoadMenuDesignSettings(void)
12354 {
12355   char *filename_base = UNDEFINED_FILENAME, *filename_local;
12356
12357   InitMenuDesignSettings_Static();
12358   InitMenuDesignSettings_SpecialPreProcessing();
12359
12360   if (!GFX_OVERRIDE_ARTWORK(ARTWORK_TYPE_GRAPHICS))
12361   {
12362     // first look for special settings configured in level series config
12363     filename_base = getCustomArtworkLevelConfigFilename(ARTWORK_TYPE_GRAPHICS);
12364
12365     if (fileExists(filename_base))
12366       LoadMenuDesignSettingsFromFilename(filename_base);
12367   }
12368
12369   filename_local = getCustomArtworkConfigFilename(ARTWORK_TYPE_GRAPHICS);
12370
12371   if (filename_local != NULL && !strEqual(filename_base, filename_local))
12372     LoadMenuDesignSettingsFromFilename(filename_local);
12373
12374   InitMenuDesignSettings_SpecialPostProcessing();
12375 }
12376
12377 void LoadMenuDesignSettings_AfterGraphics(void)
12378 {
12379   InitMenuDesignSettings_SpecialPostProcessing_AfterGraphics();
12380 }
12381
12382 void LoadUserDefinedEditorElementList(int **elements, int *num_elements)
12383 {
12384   char *filename = getEditorSetupFilename();
12385   SetupFileList *setup_file_list, *list;
12386   SetupFileHash *element_hash;
12387   int num_unknown_tokens = 0;
12388   int i;
12389
12390   if ((setup_file_list = loadSetupFileList(filename)) == NULL)
12391     return;
12392
12393   element_hash = newSetupFileHash();
12394
12395   for (i = 0; i < NUM_FILE_ELEMENTS; i++)
12396     setHashEntry(element_hash, element_info[i].token_name, i_to_a(i));
12397
12398   // determined size may be larger than needed (due to unknown elements)
12399   *num_elements = 0;
12400   for (list = setup_file_list; list != NULL; list = list->next)
12401     (*num_elements)++;
12402
12403   // add space for up to 3 more elements for padding that may be needed
12404   *num_elements += 3;
12405
12406   // free memory for old list of elements, if needed
12407   checked_free(*elements);
12408
12409   // allocate memory for new list of elements
12410   *elements = checked_malloc(*num_elements * sizeof(int));
12411
12412   *num_elements = 0;
12413   for (list = setup_file_list; list != NULL; list = list->next)
12414   {
12415     char *value = getHashEntry(element_hash, list->token);
12416
12417     if (value == NULL)          // try to find obsolete token mapping
12418     {
12419       char *mapped_token = get_mapped_token(list->token);
12420
12421       if (mapped_token != NULL)
12422       {
12423         value = getHashEntry(element_hash, mapped_token);
12424
12425         free(mapped_token);
12426       }
12427     }
12428
12429     if (value != NULL)
12430     {
12431       (*elements)[(*num_elements)++] = atoi(value);
12432     }
12433     else
12434     {
12435       if (num_unknown_tokens == 0)
12436       {
12437         Warn("---");
12438         Warn("unknown token(s) found in config file:");
12439         Warn("- config file: '%s'", filename);
12440
12441         num_unknown_tokens++;
12442       }
12443
12444       Warn("- token: '%s'", list->token);
12445     }
12446   }
12447
12448   if (num_unknown_tokens > 0)
12449     Warn("---");
12450
12451   while (*num_elements % 4)     // pad with empty elements, if needed
12452     (*elements)[(*num_elements)++] = EL_EMPTY;
12453
12454   freeSetupFileList(setup_file_list);
12455   freeSetupFileHash(element_hash);
12456
12457 #if 0
12458   for (i = 0; i < *num_elements; i++)
12459     Debug("editor", "element '%s' [%d]\n",
12460           element_info[(*elements)[i]].token_name, (*elements)[i]);
12461 #endif
12462 }
12463
12464 static struct MusicFileInfo *get_music_file_info_ext(char *basename, int music,
12465                                                      boolean is_sound)
12466 {
12467   SetupFileHash *setup_file_hash = NULL;
12468   struct MusicFileInfo tmp_music_file_info, *new_music_file_info;
12469   char *filename_music, *filename_prefix, *filename_info;
12470   struct
12471   {
12472     char *token;
12473     char **value_ptr;
12474   }
12475   token_to_value_ptr[] =
12476   {
12477     { "title_header",   &tmp_music_file_info.title_header       },
12478     { "artist_header",  &tmp_music_file_info.artist_header      },
12479     { "album_header",   &tmp_music_file_info.album_header       },
12480     { "year_header",    &tmp_music_file_info.year_header        },
12481
12482     { "title",          &tmp_music_file_info.title              },
12483     { "artist",         &tmp_music_file_info.artist             },
12484     { "album",          &tmp_music_file_info.album              },
12485     { "year",           &tmp_music_file_info.year               },
12486
12487     { NULL,             NULL                                    },
12488   };
12489   int i;
12490
12491   filename_music = (is_sound ? getCustomSoundFilename(basename) :
12492                     getCustomMusicFilename(basename));
12493
12494   if (filename_music == NULL)
12495     return NULL;
12496
12497   // ---------- try to replace file extension ----------
12498
12499   filename_prefix = getStringCopy(filename_music);
12500   if (strrchr(filename_prefix, '.') != NULL)
12501     *strrchr(filename_prefix, '.') = '\0';
12502   filename_info = getStringCat2(filename_prefix, ".txt");
12503
12504   if (fileExists(filename_info))
12505     setup_file_hash = loadSetupFileHash(filename_info);
12506
12507   free(filename_prefix);
12508   free(filename_info);
12509
12510   if (setup_file_hash == NULL)
12511   {
12512     // ---------- try to add file extension ----------
12513
12514     filename_prefix = getStringCopy(filename_music);
12515     filename_info = getStringCat2(filename_prefix, ".txt");
12516
12517     if (fileExists(filename_info))
12518       setup_file_hash = loadSetupFileHash(filename_info);
12519
12520     free(filename_prefix);
12521     free(filename_info);
12522   }
12523
12524   if (setup_file_hash == NULL)
12525     return NULL;
12526
12527   // ---------- music file info found ----------
12528
12529   clear_mem(&tmp_music_file_info, sizeof(struct MusicFileInfo));
12530
12531   for (i = 0; token_to_value_ptr[i].token != NULL; i++)
12532   {
12533     char *value = getHashEntry(setup_file_hash, token_to_value_ptr[i].token);
12534
12535     *token_to_value_ptr[i].value_ptr =
12536       getStringCopy(value != NULL && *value != '\0' ? value : UNKNOWN_NAME);
12537   }
12538
12539   tmp_music_file_info.basename = getStringCopy(basename);
12540   tmp_music_file_info.music = music;
12541   tmp_music_file_info.is_sound = is_sound;
12542
12543   new_music_file_info = checked_malloc(sizeof(struct MusicFileInfo));
12544   *new_music_file_info = tmp_music_file_info;
12545
12546   return new_music_file_info;
12547 }
12548
12549 static struct MusicFileInfo *get_music_file_info(char *basename, int music)
12550 {
12551   return get_music_file_info_ext(basename, music, FALSE);
12552 }
12553
12554 static struct MusicFileInfo *get_sound_file_info(char *basename, int sound)
12555 {
12556   return get_music_file_info_ext(basename, sound, TRUE);
12557 }
12558
12559 static boolean music_info_listed_ext(struct MusicFileInfo *list,
12560                                      char *basename, boolean is_sound)
12561 {
12562   for (; list != NULL; list = list->next)
12563     if (list->is_sound == is_sound && strEqual(list->basename, basename))
12564       return TRUE;
12565
12566   return FALSE;
12567 }
12568
12569 static boolean music_info_listed(struct MusicFileInfo *list, char *basename)
12570 {
12571   return music_info_listed_ext(list, basename, FALSE);
12572 }
12573
12574 static boolean sound_info_listed(struct MusicFileInfo *list, char *basename)
12575 {
12576   return music_info_listed_ext(list, basename, TRUE);
12577 }
12578
12579 void LoadMusicInfo(void)
12580 {
12581   char *music_directory = getCustomMusicDirectory();
12582   int num_music = getMusicListSize();
12583   int num_music_noconf = 0;
12584   int num_sounds = getSoundListSize();
12585   Directory *dir;
12586   DirectoryEntry *dir_entry;
12587   struct FileInfo *music, *sound;
12588   struct MusicFileInfo *next, **new;
12589   int i;
12590
12591   while (music_file_info != NULL)
12592   {
12593     next = music_file_info->next;
12594
12595     checked_free(music_file_info->basename);
12596
12597     checked_free(music_file_info->title_header);
12598     checked_free(music_file_info->artist_header);
12599     checked_free(music_file_info->album_header);
12600     checked_free(music_file_info->year_header);
12601
12602     checked_free(music_file_info->title);
12603     checked_free(music_file_info->artist);
12604     checked_free(music_file_info->album);
12605     checked_free(music_file_info->year);
12606
12607     free(music_file_info);
12608
12609     music_file_info = next;
12610   }
12611
12612   new = &music_file_info;
12613
12614   for (i = 0; i < num_music; i++)
12615   {
12616     music = getMusicListEntry(i);
12617
12618     if (music->filename == NULL)
12619       continue;
12620
12621     if (strEqual(music->filename, UNDEFINED_FILENAME))
12622       continue;
12623
12624     // a configured file may be not recognized as music
12625     if (!FileIsMusic(music->filename))
12626       continue;
12627
12628     if (!music_info_listed(music_file_info, music->filename))
12629     {
12630       *new = get_music_file_info(music->filename, i);
12631
12632       if (*new != NULL)
12633         new = &(*new)->next;
12634     }
12635   }
12636
12637   if ((dir = openDirectory(music_directory)) == NULL)
12638   {
12639     Warn("cannot read music directory '%s'", music_directory);
12640
12641     return;
12642   }
12643
12644   while ((dir_entry = readDirectory(dir)) != NULL)      // loop all entries
12645   {
12646     char *basename = dir_entry->basename;
12647     boolean music_already_used = FALSE;
12648     int i;
12649
12650     // skip all music files that are configured in music config file
12651     for (i = 0; i < num_music; i++)
12652     {
12653       music = getMusicListEntry(i);
12654
12655       if (music->filename == NULL)
12656         continue;
12657
12658       if (strEqual(basename, music->filename))
12659       {
12660         music_already_used = TRUE;
12661         break;
12662       }
12663     }
12664
12665     if (music_already_used)
12666       continue;
12667
12668     if (!FileIsMusic(dir_entry->filename))
12669       continue;
12670
12671     if (!music_info_listed(music_file_info, basename))
12672     {
12673       *new = get_music_file_info(basename, MAP_NOCONF_MUSIC(num_music_noconf));
12674
12675       if (*new != NULL)
12676         new = &(*new)->next;
12677     }
12678
12679     num_music_noconf++;
12680   }
12681
12682   closeDirectory(dir);
12683
12684   for (i = 0; i < num_sounds; i++)
12685   {
12686     sound = getSoundListEntry(i);
12687
12688     if (sound->filename == NULL)
12689       continue;
12690
12691     if (strEqual(sound->filename, UNDEFINED_FILENAME))
12692       continue;
12693
12694     // a configured file may be not recognized as sound
12695     if (!FileIsSound(sound->filename))
12696       continue;
12697
12698     if (!sound_info_listed(music_file_info, sound->filename))
12699     {
12700       *new = get_sound_file_info(sound->filename, i);
12701       if (*new != NULL)
12702         new = &(*new)->next;
12703     }
12704   }
12705 }
12706
12707 static void add_helpanim_entry(int element, int action, int direction,
12708                                int delay, int *num_list_entries)
12709 {
12710   struct HelpAnimInfo *new_list_entry;
12711   (*num_list_entries)++;
12712
12713   helpanim_info =
12714     checked_realloc(helpanim_info,
12715                     *num_list_entries * sizeof(struct HelpAnimInfo));
12716   new_list_entry = &helpanim_info[*num_list_entries - 1];
12717
12718   new_list_entry->element = element;
12719   new_list_entry->action = action;
12720   new_list_entry->direction = direction;
12721   new_list_entry->delay = delay;
12722 }
12723
12724 static void print_unknown_token(char *filename, char *token, int token_nr)
12725 {
12726   if (token_nr == 0)
12727   {
12728     Warn("---");
12729     Warn("unknown token(s) found in config file:");
12730     Warn("- config file: '%s'", filename);
12731   }
12732
12733   Warn("- token: '%s'", token);
12734 }
12735
12736 static void print_unknown_token_end(int token_nr)
12737 {
12738   if (token_nr > 0)
12739     Warn("---");
12740 }
12741
12742 void LoadHelpAnimInfo(void)
12743 {
12744   char *filename = getHelpAnimFilename();
12745   SetupFileList *setup_file_list = NULL, *list;
12746   SetupFileHash *element_hash, *action_hash, *direction_hash;
12747   int num_list_entries = 0;
12748   int num_unknown_tokens = 0;
12749   int i;
12750
12751   if (fileExists(filename))
12752     setup_file_list = loadSetupFileList(filename);
12753
12754   if (setup_file_list == NULL)
12755   {
12756     // use reliable default values from static configuration
12757     SetupFileList *insert_ptr;
12758
12759     insert_ptr = setup_file_list =
12760       newSetupFileList(helpanim_config[0].token,
12761                        helpanim_config[0].value);
12762
12763     for (i = 1; helpanim_config[i].token; i++)
12764       insert_ptr = addListEntry(insert_ptr,
12765                                 helpanim_config[i].token,
12766                                 helpanim_config[i].value);
12767   }
12768
12769   element_hash   = newSetupFileHash();
12770   action_hash    = newSetupFileHash();
12771   direction_hash = newSetupFileHash();
12772
12773   for (i = 0; i < MAX_NUM_ELEMENTS; i++)
12774     setHashEntry(element_hash, element_info[i].token_name, i_to_a(i));
12775
12776   for (i = 0; i < NUM_ACTIONS; i++)
12777     setHashEntry(action_hash, element_action_info[i].suffix,
12778                  i_to_a(element_action_info[i].value));
12779
12780   // do not store direction index (bit) here, but direction value!
12781   for (i = 0; i < NUM_DIRECTIONS_FULL; i++)
12782     setHashEntry(direction_hash, element_direction_info[i].suffix,
12783                  i_to_a(1 << element_direction_info[i].value));
12784
12785   for (list = setup_file_list; list != NULL; list = list->next)
12786   {
12787     char *element_token, *action_token, *direction_token;
12788     char *element_value, *action_value, *direction_value;
12789     int delay = atoi(list->value);
12790
12791     if (strEqual(list->token, "end"))
12792     {
12793       add_helpanim_entry(HELPANIM_LIST_NEXT, -1, -1, -1, &num_list_entries);
12794
12795       continue;
12796     }
12797
12798     /* first try to break element into element/action/direction parts;
12799        if this does not work, also accept combined "element[.act][.dir]"
12800        elements (like "dynamite.active"), which are unique elements */
12801
12802     if (strchr(list->token, '.') == NULL)       // token contains no '.'
12803     {
12804       element_value = getHashEntry(element_hash, list->token);
12805       if (element_value != NULL)        // element found
12806         add_helpanim_entry(atoi(element_value), -1, -1, delay,
12807                            &num_list_entries);
12808       else
12809       {
12810         // no further suffixes found -- this is not an element
12811         print_unknown_token(filename, list->token, num_unknown_tokens++);
12812       }
12813
12814       continue;
12815     }
12816
12817     // token has format "<prefix>.<something>"
12818
12819     action_token = strchr(list->token, '.');    // suffix may be action ...
12820     direction_token = action_token;             // ... or direction
12821
12822     element_token = getStringCopy(list->token);
12823     *strchr(element_token, '.') = '\0';
12824
12825     element_value = getHashEntry(element_hash, element_token);
12826
12827     if (element_value == NULL)          // this is no element
12828     {
12829       element_value = getHashEntry(element_hash, list->token);
12830       if (element_value != NULL)        // combined element found
12831         add_helpanim_entry(atoi(element_value), -1, -1, delay,
12832                            &num_list_entries);
12833       else
12834         print_unknown_token(filename, list->token, num_unknown_tokens++);
12835
12836       free(element_token);
12837
12838       continue;
12839     }
12840
12841     action_value = getHashEntry(action_hash, action_token);
12842
12843     if (action_value != NULL)           // action found
12844     {
12845       add_helpanim_entry(atoi(element_value), atoi(action_value), -1, delay,
12846                     &num_list_entries);
12847
12848       free(element_token);
12849
12850       continue;
12851     }
12852
12853     direction_value = getHashEntry(direction_hash, direction_token);
12854
12855     if (direction_value != NULL)        // direction found
12856     {
12857       add_helpanim_entry(atoi(element_value), -1, atoi(direction_value), delay,
12858                          &num_list_entries);
12859
12860       free(element_token);
12861
12862       continue;
12863     }
12864
12865     if (strchr(action_token + 1, '.') == NULL)
12866     {
12867       // no further suffixes found -- this is not an action nor direction
12868
12869       element_value = getHashEntry(element_hash, list->token);
12870       if (element_value != NULL)        // combined element found
12871         add_helpanim_entry(atoi(element_value), -1, -1, delay,
12872                            &num_list_entries);
12873       else
12874         print_unknown_token(filename, list->token, num_unknown_tokens++);
12875
12876       free(element_token);
12877
12878       continue;
12879     }
12880
12881     // token has format "<prefix>.<suffix>.<something>"
12882
12883     direction_token = strchr(action_token + 1, '.');
12884
12885     action_token = getStringCopy(action_token);
12886     *strchr(action_token + 1, '.') = '\0';
12887
12888     action_value = getHashEntry(action_hash, action_token);
12889
12890     if (action_value == NULL)           // this is no action
12891     {
12892       element_value = getHashEntry(element_hash, list->token);
12893       if (element_value != NULL)        // combined element found
12894         add_helpanim_entry(atoi(element_value), -1, -1, delay,
12895                            &num_list_entries);
12896       else
12897         print_unknown_token(filename, list->token, num_unknown_tokens++);
12898
12899       free(element_token);
12900       free(action_token);
12901
12902       continue;
12903     }
12904
12905     direction_value = getHashEntry(direction_hash, direction_token);
12906
12907     if (direction_value != NULL)        // direction found
12908     {
12909       add_helpanim_entry(atoi(element_value), atoi(action_value),
12910                          atoi(direction_value), delay, &num_list_entries);
12911
12912       free(element_token);
12913       free(action_token);
12914
12915       continue;
12916     }
12917
12918     // this is no direction
12919
12920     element_value = getHashEntry(element_hash, list->token);
12921     if (element_value != NULL)          // combined element found
12922       add_helpanim_entry(atoi(element_value), -1, -1, delay,
12923                          &num_list_entries);
12924     else
12925       print_unknown_token(filename, list->token, num_unknown_tokens++);
12926
12927     free(element_token);
12928     free(action_token);
12929   }
12930
12931   print_unknown_token_end(num_unknown_tokens);
12932
12933   add_helpanim_entry(HELPANIM_LIST_NEXT, -1, -1, -1, &num_list_entries);
12934   add_helpanim_entry(HELPANIM_LIST_END,  -1, -1, -1, &num_list_entries);
12935
12936   freeSetupFileList(setup_file_list);
12937   freeSetupFileHash(element_hash);
12938   freeSetupFileHash(action_hash);
12939   freeSetupFileHash(direction_hash);
12940
12941 #if 0
12942   for (i = 0; i < num_list_entries; i++)
12943     Debug("files:LoadHelpAnimInfo", "'%s': %d, %d, %d => %d",
12944           EL_NAME(helpanim_info[i].element),
12945           helpanim_info[i].element,
12946           helpanim_info[i].action,
12947           helpanim_info[i].direction,
12948           helpanim_info[i].delay);
12949 #endif
12950 }
12951
12952 void LoadHelpTextInfo(void)
12953 {
12954   char *filename = getHelpTextFilename();
12955   int i;
12956
12957   if (helptext_info != NULL)
12958   {
12959     freeSetupFileHash(helptext_info);
12960     helptext_info = NULL;
12961   }
12962
12963   if (fileExists(filename))
12964     helptext_info = loadSetupFileHash(filename);
12965
12966   if (helptext_info == NULL)
12967   {
12968     // use reliable default values from static configuration
12969     helptext_info = newSetupFileHash();
12970
12971     for (i = 0; helptext_config[i].token; i++)
12972       setHashEntry(helptext_info,
12973                    helptext_config[i].token,
12974                    helptext_config[i].value);
12975   }
12976
12977 #if 0
12978   BEGIN_HASH_ITERATION(helptext_info, itr)
12979   {
12980     Debug("files:LoadHelpTextInfo", "'%s' => '%s'",
12981           HASH_ITERATION_TOKEN(itr), HASH_ITERATION_VALUE(itr));
12982   }
12983   END_HASH_ITERATION(hash, itr)
12984 #endif
12985 }
12986
12987
12988 // ----------------------------------------------------------------------------
12989 // convert levels
12990 // ----------------------------------------------------------------------------
12991
12992 #define MAX_NUM_CONVERT_LEVELS          1000
12993
12994 void ConvertLevels(void)
12995 {
12996   static LevelDirTree *convert_leveldir = NULL;
12997   static int convert_level_nr = -1;
12998   static int num_levels_handled = 0;
12999   static int num_levels_converted = 0;
13000   static boolean levels_failed[MAX_NUM_CONVERT_LEVELS];
13001   int i;
13002
13003   convert_leveldir = getTreeInfoFromIdentifier(leveldir_first,
13004                                                global.convert_leveldir);
13005
13006   if (convert_leveldir == NULL)
13007     Fail("no such level identifier: '%s'", global.convert_leveldir);
13008
13009   leveldir_current = convert_leveldir;
13010
13011   if (global.convert_level_nr != -1)
13012   {
13013     convert_leveldir->first_level = global.convert_level_nr;
13014     convert_leveldir->last_level  = global.convert_level_nr;
13015   }
13016
13017   convert_level_nr = convert_leveldir->first_level;
13018
13019   PrintLine("=", 79);
13020   Print("Converting levels\n");
13021   PrintLine("-", 79);
13022   Print("Level series identifier: '%s'\n", convert_leveldir->identifier);
13023   Print("Level series name:       '%s'\n", convert_leveldir->name);
13024   Print("Level series author:     '%s'\n", convert_leveldir->author);
13025   Print("Number of levels:        %d\n",   convert_leveldir->levels);
13026   PrintLine("=", 79);
13027   Print("\n");
13028
13029   for (i = 0; i < MAX_NUM_CONVERT_LEVELS; i++)
13030     levels_failed[i] = FALSE;
13031
13032   while (convert_level_nr <= convert_leveldir->last_level)
13033   {
13034     char *level_filename;
13035     boolean new_level;
13036
13037     level_nr = convert_level_nr++;
13038
13039     Print("Level %03d: ", level_nr);
13040
13041     LoadLevel(level_nr);
13042     if (level.no_level_file || level.no_valid_file)
13043     {
13044       Print("(no level)\n");
13045       continue;
13046     }
13047
13048     Print("converting level ... ");
13049
13050     level_filename = getDefaultLevelFilename(level_nr);
13051     new_level = !fileExists(level_filename);
13052
13053     if (new_level)
13054     {
13055       SaveLevel(level_nr);
13056
13057       num_levels_converted++;
13058
13059       Print("converted.\n");
13060     }
13061     else
13062     {
13063       if (level_nr >= 0 && level_nr < MAX_NUM_CONVERT_LEVELS)
13064         levels_failed[level_nr] = TRUE;
13065
13066       Print("NOT CONVERTED -- LEVEL ALREADY EXISTS.\n");
13067     }
13068
13069     num_levels_handled++;
13070   }
13071
13072   Print("\n");
13073   PrintLine("=", 79);
13074   Print("Number of levels handled: %d\n", num_levels_handled);
13075   Print("Number of levels converted: %d (%d%%)\n", num_levels_converted,
13076          (num_levels_handled ?
13077           num_levels_converted * 100 / num_levels_handled : 0));
13078   PrintLine("-", 79);
13079   Print("Summary (for automatic parsing by scripts):\n");
13080   Print("LEVELDIR '%s', CONVERTED %d/%d (%d%%)",
13081          convert_leveldir->identifier, num_levels_converted,
13082          num_levels_handled,
13083          (num_levels_handled ?
13084           num_levels_converted * 100 / num_levels_handled : 0));
13085
13086   if (num_levels_handled != num_levels_converted)
13087   {
13088     Print(", FAILED:");
13089     for (i = 0; i < MAX_NUM_CONVERT_LEVELS; i++)
13090       if (levels_failed[i])
13091         Print(" %03d", i);
13092   }
13093
13094   Print("\n");
13095   PrintLine("=", 79);
13096
13097   CloseAllAndExit(0);
13098 }
13099
13100
13101 // ----------------------------------------------------------------------------
13102 // create and save images for use in level sketches (raw BMP format)
13103 // ----------------------------------------------------------------------------
13104
13105 void CreateLevelSketchImages(void)
13106 {
13107   Bitmap *bitmap1;
13108   Bitmap *bitmap2;
13109   int i;
13110
13111   InitElementPropertiesGfxElement();
13112
13113   bitmap1 = CreateBitmap(TILEX, TILEY, DEFAULT_DEPTH);
13114   bitmap2 = CreateBitmap(MINI_TILEX, MINI_TILEY, DEFAULT_DEPTH);
13115
13116   for (i = 0; i < NUM_FILE_ELEMENTS; i++)
13117   {
13118     int element = getMappedElement(i);
13119     char basename1[16];
13120     char basename2[16];
13121     char *filename1;
13122     char *filename2;
13123
13124     sprintf(basename1, "%04d.bmp", i);
13125     sprintf(basename2, "%04ds.bmp", i);
13126
13127     filename1 = getPath2(global.create_sketch_images_dir, basename1);
13128     filename2 = getPath2(global.create_sketch_images_dir, basename2);
13129
13130     DrawSizedElement(0, 0, element, TILESIZE);
13131     BlitBitmap(drawto, bitmap1, SX, SY, TILEX, TILEY, 0, 0);
13132
13133     if (SDL_SaveBMP(bitmap1->surface, filename1) != 0)
13134       Fail("cannot save level sketch image file '%s'", filename1);
13135
13136     DrawSizedElement(0, 0, element, MINI_TILESIZE);
13137     BlitBitmap(drawto, bitmap2, SX, SY, MINI_TILEX, MINI_TILEY, 0, 0);
13138
13139     if (SDL_SaveBMP(bitmap2->surface, filename2) != 0)
13140       Fail("cannot save level sketch image file '%s'", filename2);
13141
13142     free(filename1);
13143     free(filename2);
13144
13145     // create corresponding SQL statements (for normal and small images)
13146     if (i < 1000)
13147     {
13148       printf("insert into phpbb_words values (NULL, '`%03d', '<IMG class=\"levelsketch\" src=\"/I/%04d.png\"/>');\n", i, i);
13149       printf("insert into phpbb_words values (NULL, '¸%03d', '<IMG class=\"levelsketch\" src=\"/I/%04ds.png\"/>');\n", i, i);
13150     }
13151
13152     printf("insert into phpbb_words values (NULL, '`%04d', '<IMG class=\"levelsketch\" src=\"/I/%04d.png\"/>');\n", i, i);
13153     printf("insert into phpbb_words values (NULL, '¸%04d', '<IMG class=\"levelsketch\" src=\"/I/%04ds.png\"/>');\n", i, i);
13154
13155     // optional: create content for forum level sketch demonstration post
13156     if (options.debug)
13157       fprintf(stderr, "%03d `%03d%c", i, i, (i % 10 < 9 ? ' ' : '\n'));
13158   }
13159
13160   FreeBitmap(bitmap1);
13161   FreeBitmap(bitmap2);
13162
13163   if (options.debug)
13164     fprintf(stderr, "\n");
13165
13166   Info("%d normal and small images created", NUM_FILE_ELEMENTS);
13167
13168   CloseAllAndExit(0);
13169 }
13170
13171
13172 // ----------------------------------------------------------------------------
13173 // create and save images for element collecting animations (raw BMP format)
13174 // ----------------------------------------------------------------------------
13175
13176 static boolean createCollectImage(int element)
13177 {
13178   return (IS_COLLECTIBLE(element) && !IS_SP_ELEMENT(element));
13179 }
13180
13181 void CreateCollectElementImages(void)
13182 {
13183   int i, j;
13184   int num_steps = 8;
13185   int anim_frames = num_steps - 1;
13186   int tile_size = TILESIZE;
13187   int anim_width  = tile_size * anim_frames;
13188   int anim_height = tile_size;
13189   int num_collect_images = 0;
13190   int pos_collect_images = 0;
13191
13192   for (i = 0; i < MAX_NUM_ELEMENTS; i++)
13193     if (createCollectImage(i))
13194       num_collect_images++;
13195
13196   Info("Creating %d element collecting animation images ...",
13197        num_collect_images);
13198
13199   int dst_width  = anim_width * 2;
13200   int dst_height = anim_height * num_collect_images / 2;
13201   Bitmap *dst_bitmap = CreateBitmap(dst_width, dst_height, DEFAULT_DEPTH);
13202   char *basename = "RocksCollect.bmp";
13203   char *filename = getPath2(global.create_collect_images_dir, basename);
13204
13205   for (i = 0; i < MAX_NUM_ELEMENTS; i++)
13206   {
13207     if (!createCollectImage(i))
13208       continue;
13209
13210     int dst_x = (pos_collect_images / (num_collect_images / 2)) * anim_width;
13211     int dst_y = (pos_collect_images % (num_collect_images / 2)) * anim_height;
13212     int graphic = el2img(i);
13213     char *token_name = element_info[i].token_name;
13214     Bitmap *tmp_bitmap = CreateBitmap(tile_size, tile_size, DEFAULT_DEPTH);
13215     Bitmap *src_bitmap;
13216     int src_x, src_y;
13217
13218     Info("- creating collecting image for '%s' ...", token_name);
13219
13220     getGraphicSource(graphic, 0, &src_bitmap, &src_x, &src_y);
13221
13222     BlitBitmap(src_bitmap, tmp_bitmap, src_x, src_y,
13223                tile_size, tile_size, 0, 0);
13224
13225     tmp_bitmap->surface_masked = tmp_bitmap->surface;
13226
13227     for (j = 0; j < anim_frames; j++)
13228     {
13229       int frame_size_final = tile_size * (anim_frames - j) / num_steps;
13230       int frame_size = frame_size_final * num_steps;
13231       int offset = (tile_size - frame_size_final) / 2;
13232       Bitmap *frame_bitmap = ZoomBitmap(tmp_bitmap, frame_size, frame_size);
13233
13234       while (frame_size > frame_size_final)
13235       {
13236         frame_size /= 2;
13237
13238         Bitmap *half_bitmap = ZoomBitmap(frame_bitmap, frame_size, frame_size);
13239
13240         FreeBitmap(frame_bitmap);
13241
13242         frame_bitmap = half_bitmap;
13243       }
13244
13245       BlitBitmap(frame_bitmap, dst_bitmap, 0, 0,
13246                  frame_size_final, frame_size_final,
13247                  dst_x + j * tile_size + offset, dst_y + offset);
13248
13249       FreeBitmap(frame_bitmap);
13250     }
13251
13252     tmp_bitmap->surface_masked = NULL;
13253
13254     FreeBitmap(tmp_bitmap);
13255
13256     pos_collect_images++;
13257   }
13258
13259   if (SDL_SaveBMP(dst_bitmap->surface, filename) != 0)
13260     Fail("cannot save element collecting image file '%s'", filename);
13261
13262   FreeBitmap(dst_bitmap);
13263
13264   Info("Done.");
13265
13266   CloseAllAndExit(0);
13267 }
13268
13269
13270 // ----------------------------------------------------------------------------
13271 // create and save images for custom and group elements (raw BMP format)
13272 // ----------------------------------------------------------------------------
13273
13274 void CreateCustomElementImages(char *directory)
13275 {
13276   char *src_basename = "RocksCE-template.ilbm";
13277   char *dst_basename = "RocksCE.bmp";
13278   char *src_filename = getPath2(directory, src_basename);
13279   char *dst_filename = getPath2(directory, dst_basename);
13280   Bitmap *src_bitmap;
13281   Bitmap *bitmap;
13282   int yoffset_ce = 0;
13283   int yoffset_ge = (TILEY * NUM_CUSTOM_ELEMENTS / 16);
13284   int i;
13285
13286   InitVideoDefaults();
13287
13288   ReCreateBitmap(&backbuffer, video.width, video.height);
13289
13290   src_bitmap = LoadImage(src_filename);
13291
13292   bitmap = CreateBitmap(TILEX * 16 * 2,
13293                         TILEY * (NUM_CUSTOM_ELEMENTS + NUM_GROUP_ELEMENTS) / 16,
13294                         DEFAULT_DEPTH);
13295
13296   for (i = 0; i < NUM_CUSTOM_ELEMENTS; i++)
13297   {
13298     int x = i % 16;
13299     int y = i / 16;
13300     int ii = i + 1;
13301     int j;
13302
13303     BlitBitmap(src_bitmap, bitmap, 0, 0, TILEX, TILEY,
13304                TILEX * x, TILEY * y + yoffset_ce);
13305
13306     BlitBitmap(src_bitmap, bitmap, 0, TILEY,
13307                TILEX, TILEY,
13308                TILEX * x + TILEX * 16,
13309                TILEY * y + yoffset_ce);
13310
13311     for (j = 2; j >= 0; j--)
13312     {
13313       int c = ii % 10;
13314
13315       BlitBitmap(src_bitmap, bitmap,
13316                  TILEX + c * 7, 0, 6, 10,
13317                  TILEX * x + 6 + j * 7,
13318                  TILEY * y + 11 + yoffset_ce);
13319
13320       BlitBitmap(src_bitmap, bitmap,
13321                  TILEX + c * 8, TILEY, 6, 10,
13322                  TILEX * 16 + TILEX * x + 6 + j * 8,
13323                  TILEY * y + 10 + yoffset_ce);
13324
13325       ii /= 10;
13326     }
13327   }
13328
13329   for (i = 0; i < NUM_GROUP_ELEMENTS; i++)
13330   {
13331     int x = i % 16;
13332     int y = i / 16;
13333     int ii = i + 1;
13334     int j;
13335
13336     BlitBitmap(src_bitmap, bitmap, 0, 0, TILEX, TILEY,
13337                TILEX * x, TILEY * y + yoffset_ge);
13338
13339     BlitBitmap(src_bitmap, bitmap, 0, TILEY,
13340                TILEX, TILEY,
13341                TILEX * x + TILEX * 16,
13342                TILEY * y + yoffset_ge);
13343
13344     for (j = 1; j >= 0; j--)
13345     {
13346       int c = ii % 10;
13347
13348       BlitBitmap(src_bitmap, bitmap, TILEX + c * 10, 11, 10, 10,
13349                  TILEX * x + 6 + j * 10,
13350                  TILEY * y + 11 + yoffset_ge);
13351
13352       BlitBitmap(src_bitmap, bitmap,
13353                  TILEX + c * 8, TILEY + 12, 6, 10,
13354                  TILEX * 16 + TILEX * x + 10 + j * 8,
13355                  TILEY * y + 10 + yoffset_ge);
13356
13357       ii /= 10;
13358     }
13359   }
13360
13361   if (SDL_SaveBMP(bitmap->surface, dst_filename) != 0)
13362     Fail("cannot save CE graphics file '%s'", dst_filename);
13363
13364   FreeBitmap(bitmap);
13365
13366   CloseAllAndExit(0);
13367 }