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