51ac2f61c3d2c869c55863576e83d03cca1d29ad
[rocksndiamonds.git] / src / tape.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 // tape.c
10 // ============================================================================
11
12 #include "libgame/libgame.h"
13
14 #include "tape.h"
15 #include "init.h"
16 #include "game.h"
17 #include "tools.h"
18 #include "files.h"
19 #include "network.h"
20 #include "anim.h"
21
22 #define DEBUG_TAPE_WHEN_PLAYING                 FALSE
23
24 // tape button identifiers
25 #define TAPE_CTRL_ID_EJECT                      0
26 #define TAPE_CTRL_ID_EXTRA                      1
27 #define TAPE_CTRL_ID_STOP                       2
28 #define TAPE_CTRL_ID_PAUSE                      3
29 #define TAPE_CTRL_ID_RECORD                     4
30 #define TAPE_CTRL_ID_PLAY                       5
31 #define TAPE_CTRL_ID_INSERT_SOLUTION            6
32 #define TAPE_CTRL_ID_PLAY_SOLUTION              7
33
34 #define NUM_TAPE_BUTTONS                        8
35
36 // values for tape handling
37 #define TAPE_PAUSE_SECONDS_BEFORE_DEATH         5
38 #define TAPE_MIN_SECONDS_FOR_UNDO_BUFFER        20
39
40 // forward declaration for internal use
41 static void HandleTapeButtons(struct GadgetInfo *);
42 static void TapeStopWarpForward(void);
43 static float GetTapeLengthSecondsFloat(void);
44 static void CopyTapeToUndoBuffer(void);
45
46 static struct GadgetInfo *tape_gadget[NUM_TAPE_BUTTONS];
47 static struct TapeInfo tape_undo_buffer;
48
49
50 // ============================================================================
51 // video tape definitions
52 // ============================================================================
53
54 #define VIDEO_INFO_OFF                  (VIDEO_STATE_DATE_OFF   |       \
55                                          VIDEO_STATE_TIME_OFF   |       \
56                                          VIDEO_STATE_FRAME_OFF)
57 #define VIDEO_STATE_OFF                 (VIDEO_STATE_PLAY_OFF   |       \
58                                          VIDEO_STATE_REC_OFF    |       \
59                                          VIDEO_STATE_PAUSE_OFF  |       \
60                                          VIDEO_STATE_FFWD_OFF   |       \
61                                          VIDEO_STATE_WARP_OFF   |       \
62                                          VIDEO_STATE_WARP2_OFF  |       \
63                                          VIDEO_STATE_PBEND_OFF  |       \
64                                          VIDEO_STATE_1STEP_OFF)
65 #define VIDEO_PRESS_OFF                 (VIDEO_PRESS_PLAY_OFF   |       \
66                                          VIDEO_PRESS_REC_OFF    |       \
67                                          VIDEO_PRESS_PAUSE_OFF  |       \
68                                          VIDEO_PRESS_STOP_OFF   |       \
69                                          VIDEO_PRESS_EJECT_OFF)
70 #define VIDEO_ALL_OFF                   (VIDEO_INFO_OFF         |       \
71                                          VIDEO_STATE_OFF        |       \
72                                          VIDEO_PRESS_OFF)
73
74 #define VIDEO_INFO_ON                   (VIDEO_STATE_DATE_ON    |       \
75                                          VIDEO_STATE_TIME_ON    |       \
76                                          VIDEO_STATE_FRAME_ON)
77 #define VIDEO_STATE_ON                  (VIDEO_STATE_PLAY_ON    |       \
78                                          VIDEO_STATE_REC_ON     |       \
79                                          VIDEO_STATE_PAUSE_ON   |       \
80                                          VIDEO_STATE_FFWD_ON    |       \
81                                          VIDEO_STATE_WARP_ON    |       \
82                                          VIDEO_STATE_WARP2_ON   |       \
83                                          VIDEO_STATE_PBEND_ON   |       \
84                                          VIDEO_STATE_1STEP_ON)
85 #define VIDEO_PRESS_ON                  (VIDEO_PRESS_PLAY_ON    |       \
86                                          VIDEO_PRESS_REC_ON     |       \
87                                          VIDEO_PRESS_PAUSE_ON   |       \
88                                          VIDEO_PRESS_STOP_ON    |       \
89                                          VIDEO_PRESS_EJECT_ON)
90 #define VIDEO_ALL_ON                    (VIDEO_INFO_ON          |       \
91                                          VIDEO_STATE_ON         |       \
92                                          VIDEO_PRESS_ON)
93
94 #define VIDEO_INFO                      (VIDEO_INFO_ON | VIDEO_INFO_OFF)
95 #define VIDEO_STATE                     (VIDEO_STATE_ON | VIDEO_STATE_OFF)
96 #define VIDEO_PRESS                     (VIDEO_PRESS_ON | VIDEO_PRESS_OFF)
97 #define VIDEO_ALL                       (VIDEO_ALL_ON | VIDEO_ALL_OFF)
98
99 #define NUM_TAPE_FUNCTIONS              11
100 #define NUM_TAPE_FUNCTION_PARTS         2
101 #define NUM_TAPE_FUNCTION_STATES        2
102
103
104 // ============================================================================
105 // video display functions
106 // ============================================================================
107
108 static void DrawVideoDisplay_Graphics(unsigned int state, unsigned int value)
109 {
110   int i, j, k;
111
112   static struct
113   {
114     int graphic;
115     struct XY *pos;
116   }
117   video_pos[NUM_TAPE_FUNCTIONS][NUM_TAPE_FUNCTION_PARTS] =
118   {
119     {
120       { IMG_GFX_TAPE_LABEL_PLAY,                &tape.label.play        },
121       { IMG_GFX_TAPE_SYMBOL_PLAY,               &tape.symbol.play       },
122     },
123     {
124       { IMG_GFX_TAPE_LABEL_RECORD,              &tape.label.record      },
125       { IMG_GFX_TAPE_SYMBOL_RECORD,             &tape.symbol.record     },
126     },
127     {
128       { IMG_GFX_TAPE_LABEL_PAUSE,               &tape.label.pause       },
129       { IMG_GFX_TAPE_SYMBOL_PAUSE,              &tape.symbol.pause      },
130     },
131     {
132       { IMG_GFX_TAPE_LABEL_DATE,                &tape.label.date        },
133       { -1,                                     NULL                    },
134     },
135     {
136       { IMG_GFX_TAPE_LABEL_TIME,                &tape.label.time        },
137       { -1,                                     NULL                    },
138     },
139     {
140       // (no label for displaying optional frame)
141       { -1,                                     NULL                    },
142       { -1,                                     NULL                    },
143     },
144     {
145       { IMG_GFX_TAPE_LABEL_FAST_FORWARD,        &tape.label.fast_forward  },
146       { IMG_GFX_TAPE_SYMBOL_FAST_FORWARD,       &tape.symbol.fast_forward },
147     },
148     {
149       { IMG_GFX_TAPE_LABEL_WARP_FORWARD,        &tape.label.warp_forward  },
150       { IMG_GFX_TAPE_SYMBOL_WARP_FORWARD,       &tape.symbol.warp_forward },
151     },
152     {
153       { IMG_GFX_TAPE_LABEL_WARP_FORWARD_BLIND,  &tape.label.warp_forward_blind},
154       { IMG_GFX_TAPE_SYMBOL_WARP_FORWARD_BLIND, &tape.symbol.warp_forward_blind},
155     },
156     {
157       { IMG_GFX_TAPE_LABEL_PAUSE_BEFORE_END,    &tape.label.pause_before_end  },
158       { IMG_GFX_TAPE_SYMBOL_PAUSE_BEFORE_END,   &tape.symbol.pause_before_end },
159     },
160     {
161       { IMG_GFX_TAPE_LABEL_SINGLE_STEP,         &tape.label.single_step  },
162       { IMG_GFX_TAPE_SYMBOL_SINGLE_STEP,        &tape.symbol.single_step },
163     },
164   };
165
166   for (k = 0; k < NUM_TAPE_FUNCTION_STATES; k++)        // on or off states
167   {
168     for (i = 0; i < NUM_TAPE_FUNCTIONS; i++)            // record, play, ...
169     {
170       for (j = 0; j < NUM_TAPE_FUNCTION_PARTS; j++)     // label or symbol
171       {
172         int graphic = video_pos[i][j].graphic;
173         struct XY *pos = video_pos[i][j].pos;
174
175         if (graphic == -1 ||
176             pos->x == -1 ||
177             pos->y == -1)
178           continue;
179
180         if (state & (1 << (i * 2 + k)))
181         {
182           struct GraphicInfo *gfx_bg = &graphic_info[IMG_BACKGROUND_TAPE];
183           struct GraphicInfo *gfx = &graphic_info[graphic];
184           Bitmap *gd_bitmap;
185           int gd_x, gd_y;
186           int skip_value =
187             (j == 0 ? VIDEO_DISPLAY_SYMBOL_ONLY : VIDEO_DISPLAY_LABEL_ONLY);
188
189           if (value == skip_value)
190             continue;
191
192           if (k == 1)           // on
193           {
194             gd_bitmap = gfx->bitmap;
195             gd_x = gfx->src_x;
196             gd_y = gfx->src_y;
197           }
198           else                  // off
199           {
200             gd_bitmap = gfx_bg->bitmap;
201             gd_x = gfx_bg->src_x + pos->x;
202             gd_y = gfx_bg->src_y + pos->y;
203           }
204
205           // some tape graphics may be undefined -- only draw if defined
206           if (gd_bitmap != NULL)
207             BlitBitmap(gd_bitmap, drawto, gd_x, gd_y, gfx->width, gfx->height,
208                        VX + pos->x, VY + pos->y);
209
210           redraw_mask |= REDRAW_DOOR_2;
211         }
212       }
213     }
214   }
215 }
216
217
218 #define DATETIME_NONE                   (0)
219
220 #define DATETIME_DATE_YYYY              (1 << 0)
221 #define DATETIME_DATE_YY                (1 << 1)
222 #define DATETIME_DATE_MON               (1 << 2)
223 #define DATETIME_DATE_MM                (1 << 3)
224 #define DATETIME_DATE_DD                (1 << 4)
225
226 #define DATETIME_TIME_HH                (1 << 5)
227 #define DATETIME_TIME_MIN               (1 << 6)
228 #define DATETIME_TIME_MM                (1 << 7)
229 #define DATETIME_TIME_SS                (1 << 8)
230
231 #define DATETIME_FRAME                  (1 << 9)
232
233 #define DATETIME_XOFFSET_1              (1 << 10)
234 #define DATETIME_XOFFSET_2              (1 << 11)
235
236 #define DATETIME_DATE                   (DATETIME_DATE_YYYY     |       \
237                                          DATETIME_DATE_YY       |       \
238                                          DATETIME_DATE_MON      |       \
239                                          DATETIME_DATE_MM       |       \
240                                          DATETIME_DATE_DD)
241
242 #define DATETIME_TIME                   (DATETIME_TIME_HH       |       \
243                                          DATETIME_TIME_MIN      |       \
244                                          DATETIME_TIME_MM       |       \
245                                          DATETIME_TIME_SS)
246
247 #define MAX_DATETIME_STRING_SIZE        32
248
249 static void DrawVideoDisplay_DateTime(unsigned int state, unsigned int value)
250 {
251   int i;
252
253   static char *month_shortnames[] =
254   {
255     "JAN",
256     "FEB",
257     "MAR",
258     "APR",
259     "MAY",
260     "JUN",
261     "JUL",
262     "AUG",
263     "SEP",
264     "OCT",
265     "NOV",
266     "DEC"
267   };
268
269   static struct
270   {
271     struct TextPosInfo *pos;
272     int type;
273   }
274   datetime_info[] =
275   {
276     { &tape.text.date,          DATETIME_DATE_DD                        },
277     { &tape.text.date,          DATETIME_DATE_MON | DATETIME_XOFFSET_1  },
278     { &tape.text.date,          DATETIME_DATE_YY  | DATETIME_XOFFSET_2  },
279     { &tape.text.date_yyyy,     DATETIME_DATE_YYYY                      },
280     { &tape.text.date_yy,       DATETIME_DATE_YY                        },
281     { &tape.text.date_mon,      DATETIME_DATE_MON                       },
282     { &tape.text.date_mm,       DATETIME_DATE_MM                        },
283     { &tape.text.date_dd,       DATETIME_DATE_DD                        },
284
285     { &tape.text.time,          DATETIME_TIME_MIN                       },
286     { &tape.text.time,          DATETIME_TIME_SS  | DATETIME_XOFFSET_1  },
287     { &tape.text.time_hh,       DATETIME_TIME_HH                        },
288     { &tape.text.time_mm,       DATETIME_TIME_MM                        },
289     { &tape.text.time_ss,       DATETIME_TIME_SS                        },
290
291     { &tape.text.frame,         DATETIME_FRAME                          },
292
293     { NULL,                     DATETIME_NONE                           },
294   };
295
296   for (i = 0; datetime_info[i].pos != NULL; i++)
297   {
298     struct TextPosInfo *pos = datetime_info[i].pos;
299     int type = datetime_info[i].type;
300     int xpos, ypos;
301
302     if (pos->x == -1 &&
303         pos->y == -1)
304       continue;
305
306     xpos = VX + pos->x + (type & DATETIME_XOFFSET_1 ? pos->xoffset  :
307                           type & DATETIME_XOFFSET_2 ? pos->xoffset2 : 0);
308     ypos = VY + pos->y;
309
310     if ((type & DATETIME_DATE) && (state & VIDEO_STATE_DATE_ON))
311     {
312       char s[MAX_DATETIME_STRING_SIZE];
313       int year2 = value / 10000;
314       int year4 = (year2 < 70 ? 2000 + year2 : 1900 + year2);
315       int month_index_raw = (value / 100) % 100;
316       int month_index = month_index_raw % 12;   // prevent invalid index
317       int month = month_index + 1;
318       int day = value % 100;
319
320       strcpy(s, (type & DATETIME_DATE_YYYY ? int2str(year4, 4) :
321                  type & DATETIME_DATE_YY   ? int2str(year2, 2) :
322                  type & DATETIME_DATE_MON  ? month_shortnames[month_index] :
323                  type & DATETIME_DATE_MM   ? int2str(month, 2) :
324                  type & DATETIME_DATE_DD   ? int2str(day, 2) : ""));
325
326       DrawText(xpos, ypos, s, pos->font);
327     }
328     else if ((type & DATETIME_TIME) && (state & VIDEO_STATE_TIME_ON))
329     {
330       char s[MAX_DATETIME_STRING_SIZE];
331       int hh = (value / 3600) % 100;
332       int min = value / 60;
333       int mm = (value / 60) % 60;
334       int ss = value % 60;
335
336       strcpy(s, (type & DATETIME_TIME_HH  ? int2str(hh, 2) :
337                  type & DATETIME_TIME_MIN ? int2str(min, 2) :
338                  type & DATETIME_TIME_MM  ? int2str(mm, 2) :
339                  type & DATETIME_TIME_SS  ? int2str(ss, 2) : ""));
340
341       DrawText(xpos, ypos, s, pos->font);
342     }
343     else if ((type & DATETIME_FRAME) && (state & VIDEO_STATE_FRAME_ON))
344     {
345       DrawText(xpos, ypos, int2str(value, pos->size), pos->font);
346     }
347   }
348 }
349
350 void DrawVideoDisplay(unsigned int state, unsigned int value)
351 {
352   DrawVideoDisplay_Graphics(state, value);
353   DrawVideoDisplay_DateTime(state, value);
354 }
355
356 static void DrawVideoDisplayLabel(unsigned int state)
357 {
358   DrawVideoDisplay(state, VIDEO_DISPLAY_LABEL_ONLY);
359 }
360
361 static void DrawVideoDisplaySymbol(unsigned int state)
362 {
363   DrawVideoDisplay(state, VIDEO_DISPLAY_SYMBOL_ONLY);
364 }
365
366 static void DrawVideoDisplayCurrentState(void)
367 {
368   int state = 0;
369
370   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
371
372   if (tape.pausing)
373     state |= VIDEO_STATE_PAUSE_ON;
374
375   if (tape.recording)
376   {
377     state |= VIDEO_STATE_REC_ON;
378
379     if (tape.single_step)
380       state |= VIDEO_STATE_1STEP_ON;
381   }
382   else if (tape.playing)
383   {
384     state |= VIDEO_STATE_PLAY_ON;
385
386     if (!tape.pausing)
387     {
388       if (tape.deactivate_display)
389         state |= VIDEO_STATE_WARP2_ON;
390       else if (tape.warp_forward)
391         state |= VIDEO_STATE_WARP_ON;
392       else if (tape.fast_forward)
393         state |= VIDEO_STATE_FFWD_ON;
394
395       if (tape.pause_before_end)
396         state |= VIDEO_STATE_PBEND_ON;
397     }
398   }
399
400   // draw labels and symbols separately to prevent labels overlapping symbols
401   DrawVideoDisplayLabel(state);
402   DrawVideoDisplaySymbol(state);
403 }
404
405 void DrawCompleteVideoDisplay(void)
406 {
407   struct GraphicInfo *g_tape = &graphic_info[IMG_BACKGROUND_TAPE];
408
409   // draw tape background
410   BlitBitmap(g_tape->bitmap, drawto, g_tape->src_x, g_tape->src_y,
411              gfx.vxsize, gfx.vysize, gfx.vx, gfx.vy);
412
413   // draw tape buttons (forced)
414   RedrawOrRemapTapeButtons();
415
416   DrawVideoDisplay(VIDEO_ALL_OFF, 0);
417
418   if (tape.recording)
419   {
420     DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
421     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
422     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
423     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
424
425     if (tape.pausing)
426       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
427   }
428   else if (tape.playing)
429   {
430     DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
431     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
432     DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
433     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
434
435     if (tape.pausing)
436       DrawVideoDisplay(VIDEO_STATE_PAUSE_ON, 0);
437   }
438   else if (tape.date && tape.length)
439   {
440     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
441     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
442     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
443   }
444
445   BlitBitmap(drawto, bitmap_db_door_2, gfx.vx, gfx.vy, gfx.vxsize, gfx.vysize,
446              0, 0);
447 }
448
449 void TapeDeactivateDisplayOn(void)
450 {
451   SetDrawDeactivationMask(REDRAW_FIELD);
452   audio.sound_deactivated = TRUE;
453 }
454
455 void TapeDeactivateDisplayOff(boolean redraw_display)
456 {
457   SetDrawDeactivationMask(REDRAW_NONE);
458   audio.sound_deactivated = FALSE;
459
460   if (redraw_display)
461   {
462     RedrawPlayfield();
463
464     UpdateGameDoorValues();
465     DrawGameDoorValues();
466   }
467 }
468
469
470 // ============================================================================
471 // tape logging functions
472 // ============================================================================
473
474 struct AutoPlayInfo
475 {
476   LevelDirTree *leveldir;
477   boolean initialized;
478   int last_level_nr;
479   int level_nr;
480   int num_levels_played;
481   int num_levels_solved;
482   int num_tapes_patched;
483   int num_tape_missing;
484   boolean level_failed[MAX_TAPES_PER_SET];
485   char *tape_filename;
486 };
487
488 static char tape_patch_info[MAX_OUTPUT_LINESIZE];
489
490 static void PrintTapeReplayProgress(boolean replay_finished)
491 {
492   static unsigned int counter_last = -1;
493   unsigned int counter = Counter();
494   unsigned int counter_seconds  = counter / 1000;
495
496   if (!replay_finished)
497   {
498     unsigned int counter_delay = 50;
499
500     if (counter > counter_last + counter_delay)
501     {
502       PrintNoLog("\r");
503       PrintNoLog("Tape %03d %s[%02d:%02d]: [%02d:%02d] - playing tape ... ",
504                  level_nr,  tape_patch_info,
505                  tape.length_seconds / 60, tape.length_seconds % 60,
506                  TapeTime / 60, TapeTime % 60);
507
508       counter_last = counter;
509     }
510   }
511   else
512   {
513     float tape_length_seconds = GetTapeLengthSecondsFloat();
514
515     PrintNoLog("\r");
516     Print("Tape %03d %s[%02d:%02d]: (%02d:%02d.%03d / %.2f %%) - %s.\n",
517           level_nr, tape_patch_info,
518           tape.length_seconds / 60, tape.length_seconds % 60,
519           counter_seconds / 60, counter_seconds % 60, counter % 1000,
520           (float)counter / tape_length_seconds / 10,
521           tape.auto_play_level_fixed ? "solved and fixed" :
522           tape.auto_play_level_solved ? "solved" :
523           tape.auto_play_level_not_fixable ? "NOT SOLVED, NOT FIXED" :
524           "NOT SOLVED");
525
526     counter_last = -1;
527   }
528 }
529
530 static FILE *tape_log_file;
531
532 static void OpenTapeLogfile(void)
533 {
534   if (!(tape_log_file = fopen(options.tape_log_filename, MODE_WRITE)))
535     Warn("cannot write tape logfile '%s'", options.tape_log_filename);
536 }
537
538 static void WriteTapeLogfile(byte action[MAX_TAPE_ACTIONS])
539 {
540   int i;
541
542   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
543     putFile8Bit(tape_log_file, action[i]);
544 }
545
546 static void CloseTapeLogfile(void)
547 {
548   fclose(tape_log_file);
549 }
550
551
552 // ============================================================================
553 // tape control functions
554 // ============================================================================
555
556 void TapeSetDateFromEpochSeconds(time_t epoch_seconds)
557 {
558   struct tm *lt = localtime(&epoch_seconds);
559
560   tape.date = 10000 * (lt->tm_year % 100) + 100 * lt->tm_mon + lt->tm_mday;
561 }
562
563 void TapeSetDateFromNow(void)
564 {
565   TapeSetDateFromEpochSeconds(time(NULL));
566 }
567
568 void TapeErase(void)
569 {
570   int i;
571
572   CopyTapeToUndoBuffer();
573
574   tape.counter = 0;
575   tape.length = 0;
576   tape.length_frames = 0;
577   tape.length_seconds = 0;
578
579   tape.score_tape_basename[0] = '\0';
580
581   if (leveldir_current)
582   {
583     strncpy(tape.level_identifier, leveldir_current->identifier,
584             MAX_FILENAME_LEN);
585     tape.level_identifier[MAX_FILENAME_LEN] = '\0';
586   }
587
588   tape.level_nr = level_nr;
589   tape.pos[tape.counter].delay = 0;
590   tape.changed = TRUE;
591
592   tape.random_seed = InitRND(level.random_seed);
593
594   tape.file_version = FILE_VERSION_ACTUAL;
595   tape.game_version = GAME_VERSION_ACTUAL;
596   tape.engine_version = level.game_version;
597
598   tape.property_bits = TAPE_PROPERTY_NONE;
599
600   TapeSetDateFromNow();
601
602   for (i = 0; i < MAX_PLAYERS; i++)
603     tape.player_participates[i] = FALSE;
604
605   tape.centered_player_nr_next = -1;
606   tape.set_centered_player = FALSE;
607
608   // set flags for game actions to default values (may be overwritten later)
609   tape.use_key_actions = TRUE;
610   tape.use_mouse_actions = FALSE;
611 }
612
613 static void TapeRewind(void)
614 {
615   tape.counter = 0;
616   tape.delay_played = 0;
617   tape.pause_before_end = FALSE;
618   tape.recording = FALSE;
619   tape.playing = FALSE;
620   tape.fast_forward = FALSE;
621   tape.warp_forward = FALSE;
622   tape.deactivate_display = FALSE;
623   tape.auto_play = (global.autoplay_leveldir != NULL);
624   tape.auto_play_level_solved = FALSE;
625   tape.auto_play_level_fixed = FALSE;
626   tape.auto_play_level_not_fixable = FALSE;
627   tape.quick_resume = FALSE;
628   tape.single_step = FALSE;
629
630   tape.centered_player_nr_next = -1;
631   tape.set_centered_player = FALSE;
632
633   InitRND(tape.random_seed);
634 }
635
636 static void TapeSetRandomSeed(int random_seed)
637 {
638   tape.random_seed = InitRND(random_seed);
639 }
640
641 void TapeStartRecording(int random_seed)
642 {
643   if (!TAPE_IS_STOPPED(tape))
644     TapeStop();
645
646   TapeErase();
647   TapeRewind();
648   TapeSetRandomSeed(random_seed);
649
650   tape.recording = TRUE;
651
652   DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
653   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
654   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
655   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
656
657   MapTapeWarpButton();
658
659   SetDrawDeactivationMask(REDRAW_NONE);
660   audio.sound_deactivated = FALSE;
661
662   // required here to update video display if tape door is closed
663   if (GetDoorState() & DOOR_CLOSE_2)
664     OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
665 }
666
667 static void TapeStartGameRecording(void)
668 {
669   StartGameActions(network.enabled, TRUE, level.random_seed);
670 }
671
672 static void TapeAppendRecording(void)
673 {
674   if (!tape.playing || !tape.pausing)
675     return;
676
677   // stop playing
678   tape.playing = FALSE;
679   tape.fast_forward = FALSE;
680   tape.warp_forward = FALSE;
681   tape.pause_before_end = FALSE;
682   tape.deactivate_display = FALSE;
683
684   // start recording
685   tape.recording = TRUE;
686   tape.changed = TRUE;
687
688   // set current delay (for last played move)
689   tape.pos[tape.counter].delay = tape.delay_played;
690
691   tape.property_bits |= TAPE_PROPERTY_REPLAYED;
692
693   // set current date
694   TapeSetDateFromNow();
695
696   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
697   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF | VIDEO_STATE_REC_ON, 0);
698
699   UpdateAndDisplayGameControlValues();
700 }
701
702 void TapeHaltRecording(void)
703 {
704   tape.counter++;
705
706   // initialize delay for next tape entry (to be able to continue recording)
707   if (tape.counter < MAX_TAPE_LEN)
708     tape.pos[tape.counter].delay = 0;
709
710   tape.length = tape.counter;
711   tape.length_frames = GetTapeLengthFrames();
712   tape.length_seconds = GetTapeLengthSeconds();
713 }
714
715 void TapeStopRecording(void)
716 {
717   if (tape.recording)
718     TapeHaltRecording();
719
720   tape.recording = FALSE;
721   tape.pausing = FALSE;
722
723   DrawVideoDisplay(VIDEO_STATE_REC_OFF, 0);
724   MapTapeEjectButton();
725 }
726
727 boolean TapeAddAction(byte action[MAX_TAPE_ACTIONS])
728 {
729   int i;
730
731   if (tape.pos[tape.counter].delay > 0)         // already stored action
732   {
733     boolean changed_events = FALSE;
734
735     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
736       if (tape.pos[tape.counter].action[i] != action[i])
737         changed_events = TRUE;
738
739     if (changed_events || tape.pos[tape.counter].delay >= 255)
740     {
741       if (tape.counter >= MAX_TAPE_LEN - 1)
742         return FALSE;
743
744       tape.counter++;
745       tape.pos[tape.counter].delay = 0;
746     }
747     else
748       tape.pos[tape.counter].delay++;
749   }
750
751   if (tape.pos[tape.counter].delay == 0)        // store new action
752   {
753     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
754       tape.pos[tape.counter].action[i] = action[i];
755
756     tape.pos[tape.counter].delay++;
757   }
758
759   return TRUE;
760 }
761
762 void TapeRecordAction(byte action_raw[MAX_TAPE_ACTIONS])
763 {
764   byte action[MAX_TAPE_ACTIONS];
765   int i;
766
767   if (!tape.recording)          // (record action even when tape is paused)
768     return;
769
770   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
771     action[i] = action_raw[i];
772
773   if (tape.use_key_actions && tape.set_centered_player)
774   {
775     for (i = 0; i < MAX_PLAYERS; i++)
776       if (tape.centered_player_nr_next == i ||
777           tape.centered_player_nr_next == -1)
778         action[i] |= KEY_SET_FOCUS;
779
780     tape.set_centered_player = FALSE;
781   }
782
783   if (GameFrameDelay != GAME_FRAME_DELAY)
784     tape.property_bits |= TAPE_PROPERTY_GAME_SPEED;
785
786   if (setup.small_game_graphics || SCR_FIELDX >= 2 * SCR_FIELDX_DEFAULT)
787     tape.property_bits |= TAPE_PROPERTY_SMALL_GRAPHICS;
788
789   if (!TapeAddAction(action))
790     TapeStopRecording();
791 }
792
793 void TapeTogglePause(boolean toggle_mode)
794 {
795   if (tape.playing && tape.pausing && (toggle_mode & TAPE_TOGGLE_PLAY_PAUSE))
796   {
797     // continue playing in normal mode
798     tape.fast_forward = FALSE;
799     tape.warp_forward = FALSE;
800     tape.deactivate_display = FALSE;
801
802     tape.pause_before_end = FALSE;
803   }
804
805   tape.pausing = !tape.pausing;
806
807   if (tape.single_step && (toggle_mode & TAPE_TOGGLE_MANUAL))
808     tape.single_step = FALSE;
809
810   if (tape.single_step)
811     tape.property_bits |= TAPE_PROPERTY_SINGLE_STEP;
812
813   if (tape.pausing)
814     tape.property_bits |= TAPE_PROPERTY_PAUSE_MODE;
815
816   DrawVideoDisplayCurrentState();
817
818   if (tape.deactivate_display)
819   {
820     if (tape.pausing)
821       TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
822     else
823       TapeDeactivateDisplayOn();
824   }
825
826   if (tape.quick_resume)
827   {
828     tape.quick_resume = FALSE;
829
830     TapeStopWarpForward();
831     TapeAppendRecording();
832
833     if (!CheckEngineSnapshotSingle())
834       SaveEngineSnapshotSingle();
835
836     // restart step/move snapshots after quick loading tape
837     SaveEngineSnapshotToListInitial();
838
839     // do not map undo/redo buttons after quick loading tape
840     return;
841   }
842
843   if (game_status == GAME_MODE_PLAYING)
844   {
845     if (setup.show_load_save_buttons &&
846         setup.show_undo_redo_buttons &&
847         CheckEngineSnapshotList())
848     {
849       if (tape.pausing)
850         MapUndoRedoButtons();
851       else if (!tape.single_step)
852         MapLoadSaveButtons();
853     }
854
855     ModifyPauseButtons();
856   }
857 }
858
859 void TapeStartPlaying(void)
860 {
861   if (TAPE_IS_EMPTY(tape))
862     return;
863
864   if (!TAPE_IS_STOPPED(tape))
865     TapeStop();
866
867   TapeRewind();
868
869   tape.playing = TRUE;
870
871   DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
872   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
873   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
874   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
875
876   MapTapeWarpButton();
877
878   SetDrawDeactivationMask(REDRAW_NONE);
879   audio.sound_deactivated = FALSE;
880 }
881
882 static void TapeStartGamePlaying(void)
883 {
884   TapeStartPlaying();
885
886   InitGame();
887 }
888
889 void TapeStopPlaying(void)
890 {
891   tape.playing = FALSE;
892   tape.pausing = FALSE;
893
894   if (tape.warp_forward)
895     TapeStopWarpForward();
896
897   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF, 0);
898   MapTapeEjectButton();
899 }
900
901 byte *TapePlayAction(void)
902 {
903   int update_delay = FRAMES_PER_SECOND / 2;
904   boolean update_video_display = (FrameCounter % update_delay == 0);
905   boolean update_draw_label_on = ((FrameCounter / update_delay) % 2 == 1);
906   static byte action[MAX_TAPE_ACTIONS];
907   int i;
908
909   if (!tape.playing || tape.pausing)
910     return NULL;
911
912   if (tape.pause_before_end)  // stop some seconds before end of tape
913   {
914     if (TapeTime > tape.length_seconds - TAPE_PAUSE_SECONDS_BEFORE_DEATH)
915     {
916       TapeStopWarpForward();
917       TapeTogglePause(TAPE_TOGGLE_MANUAL);
918
919       return NULL;
920     }
921   }
922
923   if (tape.counter >= tape.length)      // end of tape reached
924   {
925     if (tape.warp_forward && !tape.auto_play)
926     {
927       TapeStopWarpForward();
928       TapeTogglePause(TAPE_TOGGLE_MANUAL);
929     }
930     else
931     {
932       TapeStop();
933     }
934
935     return NULL;
936   }
937
938   if (update_video_display && !tape.deactivate_display)
939   {
940     int state = 0;
941
942     if (tape.warp_forward)
943       state |= VIDEO_STATE_WARP(update_draw_label_on);
944     else if (tape.fast_forward)
945       state |= VIDEO_STATE_FFWD(update_draw_label_on);
946
947     if (tape.pause_before_end)
948       state |= VIDEO_STATE_PBEND(update_draw_label_on);
949
950     // draw labels and symbols separately to prevent labels overlapping symbols
951     DrawVideoDisplayLabel(state);
952     DrawVideoDisplaySymbol(state);
953   }
954
955   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
956     action[i] = tape.pos[tape.counter].action[i];
957
958 #if DEBUG_TAPE_WHEN_PLAYING
959   DebugContinued("", "%05d", FrameCounter);
960   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
961     DebugContinued("", "   %08x", action[i]);
962   DebugContinued("tape:play", "\n");
963 #endif
964
965   tape.set_centered_player = FALSE;
966   tape.centered_player_nr_next = -999;
967
968   if (tape.use_key_actions)
969   {
970     for (i = 0; i < MAX_PLAYERS; i++)
971     {
972       if (action[i] & KEY_SET_FOCUS)
973       {
974         tape.set_centered_player = TRUE;
975         tape.centered_player_nr_next =
976           (tape.centered_player_nr_next == -999 ? i : -1);
977       }
978
979       action[i] &= ~KEY_SET_FOCUS;
980     }
981   }
982
983   tape.delay_played++;
984   if (tape.delay_played >= tape.pos[tape.counter].delay)
985   {
986     tape.counter++;
987     tape.delay_played = 0;
988   }
989
990   if (tape.auto_play)
991     PrintTapeReplayProgress(FALSE);
992
993   if (options.tape_log_filename != NULL)
994     WriteTapeLogfile(action);
995
996   return action;
997 }
998
999 void TapeStop(void)
1000 {
1001   if (tape.pausing)
1002     TapeTogglePause(TAPE_TOGGLE_MANUAL);
1003
1004   TapeStopRecording();
1005   TapeStopPlaying();
1006
1007   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
1008
1009   if (tape.date && tape.length)
1010   {
1011     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
1012     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
1013     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
1014   }
1015 }
1016
1017 unsigned int GetTapeLengthFrames(void)
1018 {
1019   unsigned int tape_length_frames = 0;
1020   int i;
1021
1022   if (TAPE_IS_EMPTY(tape))
1023     return 0;
1024
1025   for (i = 0; i < tape.length; i++)
1026     tape_length_frames += tape.pos[i].delay;
1027
1028   return tape_length_frames;
1029 }
1030
1031 unsigned int GetTapeLengthSeconds(void)
1032 {
1033   return (GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
1034 }
1035
1036 static float GetTapeLengthSecondsFloat(void)
1037 {
1038   return ((float)GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
1039 }
1040
1041 static void TapeStartWarpForward(int mode)
1042 {
1043   tape.fast_forward = (mode & AUTOPLAY_FFWD);
1044   tape.warp_forward = (mode & AUTOPLAY_WARP);
1045   tape.deactivate_display = (mode & AUTOPLAY_WARP_NO_DISPLAY);
1046
1047   tape.pausing = FALSE;
1048
1049   if (tape.deactivate_display)
1050     TapeDeactivateDisplayOn();
1051
1052   DrawVideoDisplayCurrentState();
1053 }
1054
1055 static void TapeStopWarpForward(void)
1056 {
1057   tape.fast_forward = FALSE;
1058   tape.warp_forward = FALSE;
1059   tape.deactivate_display = FALSE;
1060
1061   tape.pause_before_end = FALSE;
1062
1063   TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
1064
1065   DrawVideoDisplayCurrentState();
1066 }
1067
1068 static void TapeSingleStep(void)
1069 {
1070   if (network.enabled)
1071     return;
1072
1073   if (!tape.pausing)
1074     TapeTogglePause(TAPE_TOGGLE_MANUAL);
1075
1076   tape.single_step = !tape.single_step;
1077
1078   DrawVideoDisplay(VIDEO_STATE_1STEP(tape.single_step), 0);
1079 }
1080
1081 void TapeQuickSave(void)
1082 {
1083   if (game_status == GAME_MODE_MAIN)
1084   {
1085     Request("No game that can be saved!", REQ_CONFIRM);
1086
1087     return;
1088   }
1089
1090   if (game_status != GAME_MODE_PLAYING)
1091     return;
1092
1093   if (tape.recording)
1094     TapeHaltRecording();        // prepare tape for saving on-the-fly
1095
1096   if (TAPE_IS_EMPTY(tape))
1097   {
1098     Request("No tape that can be saved!", REQ_CONFIRM);
1099
1100     return;
1101   }
1102
1103   tape.property_bits |= TAPE_PROPERTY_SNAPSHOT;
1104
1105   if (SaveTapeChecked(tape.level_nr))
1106     SaveEngineSnapshotSingle();
1107 }
1108
1109 void TapeQuickLoad(void)
1110 {
1111   char *filename = getTapeFilename(level_nr);
1112
1113   if (!fileExists(filename))
1114   {
1115     Request("No tape for this level!", REQ_CONFIRM);
1116
1117     return;
1118   }
1119
1120   if (tape.recording && !Request("Stop recording and load tape?",
1121                                  REQ_ASK | REQ_STAY_CLOSED))
1122   {
1123     OpenDoor(DOOR_OPEN_1 | DOOR_COPY_BACK);
1124
1125     return;
1126   }
1127
1128   if (game_status != GAME_MODE_PLAYING && game_status != GAME_MODE_MAIN)
1129     return;
1130
1131   if (CheckEngineSnapshotSingle())
1132   {
1133     TapeStartGamePlaying();
1134
1135     LoadEngineSnapshotSingle();
1136
1137     DrawCompleteVideoDisplay();
1138
1139     tape.playing = TRUE;
1140     tape.pausing = TRUE;
1141
1142     TapeStopWarpForward();
1143     TapeAppendRecording();
1144
1145     // restart step/move snapshots after quick loading tape
1146     SaveEngineSnapshotToListInitial();
1147
1148     if (FrameCounter > 0)
1149       return;
1150   }
1151
1152   TapeStop();
1153   TapeErase();
1154
1155   LoadTape(level_nr);
1156
1157   if (!TAPE_IS_EMPTY(tape))
1158   {
1159     TapeStartGamePlaying();
1160     TapeStartWarpForward(AUTOPLAY_MODE_WARP_NO_DISPLAY);
1161
1162     tape.quick_resume = TRUE;
1163     tape.property_bits |= TAPE_PROPERTY_SNAPSHOT;
1164   }
1165   else  // this should not happen (basically checked above)
1166   {
1167     int reopen_door = (game_status == GAME_MODE_PLAYING ? REQ_REOPEN : 0);
1168
1169     Request("No tape for this level!", REQ_CONFIRM | reopen_door);
1170   }
1171 }
1172
1173 boolean hasSolutionTape(void)
1174 {
1175   boolean tape_file_exists = fileExists(getSolutionTapeFilename(level_nr));
1176   boolean level_has_tape = (level.game_engine_type == GAME_ENGINE_TYPE_SP &&
1177                             level.native_sp_level->demo.is_available);
1178
1179   return (tape_file_exists || level_has_tape);
1180 }
1181
1182 boolean InsertSolutionTape(void)
1183 {
1184   if (!hasSolutionTape())
1185   {
1186     Request("No solution tape for this level!", REQ_CONFIRM);
1187
1188     return FALSE;
1189   }
1190
1191   if (!TAPE_IS_STOPPED(tape))
1192     TapeStop();
1193
1194   // if tape recorder already contains a tape, remove it without asking
1195   TapeErase();
1196
1197   LoadSolutionTape(level_nr);
1198
1199   DrawCompleteVideoDisplay();
1200
1201   if (TAPE_IS_EMPTY(tape))
1202   {
1203     Request("Loading solution tape for this level failed!", REQ_CONFIRM);
1204
1205     return FALSE;
1206   }
1207
1208   return TRUE;
1209 }
1210
1211 boolean PlaySolutionTape(void)
1212 {
1213   if (!InsertSolutionTape())
1214     return FALSE;
1215
1216   TapeStartGamePlaying();
1217
1218   return TRUE;
1219 }
1220
1221 static boolean checkTapesFromSameLevel(struct TapeInfo *t1, struct TapeInfo *t2)
1222 {
1223   return (strEqual(t1->level_identifier, t2->level_identifier) &&
1224           t1->level_nr == t2->level_nr);
1225 }
1226
1227 static void CopyTape(struct TapeInfo *tape_from, struct TapeInfo *tape_to)
1228 {
1229   *tape_to = *tape_from;
1230 }
1231
1232 static void SwapTapes(struct TapeInfo *t1, struct TapeInfo *t2)
1233 {
1234   struct TapeInfo tmp = *t1;
1235
1236   *t1 = *t2;
1237   *t2 = tmp;
1238 }
1239
1240 static void CopyTapeToUndoBuffer(void)
1241 {
1242   // copy tapes to undo buffer if large enough (or larger than last undo tape)
1243   // or if the last undo tape is from a different level set or level number
1244   if (tape.length_seconds >= TAPE_MIN_SECONDS_FOR_UNDO_BUFFER ||
1245       tape.length_seconds >= tape_undo_buffer.length_seconds ||
1246       !checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1247   {
1248     CopyTape(&tape, &tape_undo_buffer);
1249   }
1250 }
1251
1252 void UndoTape(void)
1253 {
1254   // only undo tapes from same level set and with same level number
1255   if (!checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1256     return;
1257
1258   if (!TAPE_IS_STOPPED(tape))
1259     TapeStop();
1260
1261   // swap last recorded tape with undo buffer, so undo can be reversed
1262   SwapTapes(&tape, &tape_undo_buffer);
1263
1264   DrawCompleteVideoDisplay();
1265 }
1266
1267 void FixTape_ForceSinglePlayer(void)
1268 {
1269   int i;
1270
1271   /* fix single-player tapes that contain player input for more than one
1272      player (due to a bug in 3.3.1.2 and earlier versions), which results
1273      in playing levels with more than one player in multi-player mode,
1274      even though the tape was originally recorded in single-player mode */
1275
1276   // remove player input actions for all players but the first one
1277   for (i = 1; i < MAX_PLAYERS; i++)
1278     tape.player_participates[i] = FALSE;
1279
1280   tape.changed = TRUE;
1281 }
1282
1283
1284 // ----------------------------------------------------------------------------
1285 // tape autoplay functions
1286 // ----------------------------------------------------------------------------
1287
1288 static void AutoPlayTapes_SetScoreEntry(int score, int time)
1289 {
1290   // set unique basename for score tape (for uploading to score server)
1291   strcpy(tape.score_tape_basename, getScoreTapeBasename(setup.player_name));
1292
1293   // store score in first score entry
1294   scores.last_added = 0;
1295
1296   struct ScoreEntry *entry = &scores.entry[scores.last_added];
1297
1298   strncpy(entry->tape_basename, tape.score_tape_basename, MAX_FILENAME_LEN);
1299   strncpy(entry->name, setup.player_name, MAX_PLAYER_NAME_LEN);
1300
1301   entry->score = score;
1302   entry->time = time;
1303
1304   PrintNoLog("- uploading score tape to score server ... ");
1305
1306   server_scores.uploaded = FALSE;
1307 }
1308
1309 static void AutoPlayTapes_WaitForUpload(void)
1310 {
1311   unsigned int upload_delay = 0;
1312   unsigned int upload_delay_value = 10000;
1313
1314   ResetDelayCounter(&upload_delay);
1315
1316   // wait for score tape to be successfully uploaded (and fail on timeout)
1317   while (!server_scores.uploaded)
1318   {
1319     if (DelayReached(&upload_delay, upload_delay_value))
1320     {
1321       PrintNoLog("\r");
1322       Print("- uploading score tape to score server - TIMEOUT.\n");
1323
1324       Fail("cannot upload score tape to score server");
1325     }
1326
1327     Delay(20);
1328   }
1329
1330   PrintNoLog("\r");
1331   Print("- uploading score tape to score server - uploaded.\n");
1332 }
1333
1334 void AutoPlayTapes(void)
1335 {
1336   static struct AutoPlayInfo autoplay;
1337   static int patch_nr = 0;
1338   static char *patch_name[] =
1339   {
1340     "original tape",
1341     "em_random_bug",
1342     "screen_34x34",
1343
1344     NULL
1345   };
1346   static int patch_version_first[] =
1347   {
1348     VERSION_IDENT(0,0,0,0),
1349     VERSION_IDENT(3,3,1,0),
1350     VERSION_IDENT(0,0,0,0),
1351
1352     -1
1353   };
1354   static int patch_version_last[] =
1355   {
1356     VERSION_IDENT(9,9,9,9),
1357     VERSION_IDENT(4,0,1,1),
1358     VERSION_IDENT(4,2,2,0),
1359
1360     -1
1361   };
1362   static byte patch_property_bit[] =
1363   {
1364     TAPE_PROPERTY_NONE,
1365     TAPE_PROPERTY_EM_RANDOM_BUG,
1366     TAPE_PROPERTY_NONE,
1367
1368     -1
1369   };
1370   int i;
1371
1372   if (autoplay.initialized)
1373   {
1374     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1375     {
1376       if (tape.auto_play_level_solved)
1377       {
1378         if (patch_nr > 0)
1379         {
1380           // level solved by patched tape -- save fixed tape
1381           char *filename = getTapeFilename(level_nr);
1382           char *filename_orig = getStringCat2(filename, ".orig");
1383
1384           // create backup from old tape, if not yet existing
1385           if (!fileExists(filename_orig))
1386             rename(filename, filename_orig);
1387
1388           SaveTapeToFilename(filename);
1389
1390           tape.auto_play_level_fixed = TRUE;
1391           autoplay.num_tapes_patched++;
1392         }
1393
1394         // continue with next tape
1395         patch_nr = 0;
1396       }
1397       else if (patch_name[patch_nr + 1] != NULL)
1398       {
1399         // level not solved by patched tape -- continue with next patch
1400         patch_nr++;
1401       }
1402       else
1403       {
1404         // level not solved by any patched tape -- continue with next tape
1405         tape.auto_play_level_not_fixable = TRUE;
1406         patch_nr = 0;
1407       }
1408     }
1409
1410     // just finished auto-playing tape
1411     PrintTapeReplayProgress(TRUE);
1412
1413     if (options.tape_log_filename != NULL)
1414       CloseTapeLogfile();
1415
1416     if (global.autoplay_mode == AUTOPLAY_MODE_SAVE &&
1417         tape.auto_play_level_solved)
1418     {
1419       AutoPlayTapes_SetScoreEntry(game.score_final, game.score_time_final);
1420
1421       if (leveldir_current)
1422       {
1423         // the tape's level set identifier may differ from current level set
1424         strncpy(tape.level_identifier, leveldir_current->identifier,
1425                 MAX_FILENAME_LEN);
1426         tape.level_identifier[MAX_FILENAME_LEN] = '\0';
1427
1428         // the tape's level number may differ from current level number
1429         tape.level_nr = level_nr;
1430       }
1431
1432       // save score tape to upload to server; may be required for some reasons:
1433       // * level set identifier in solution tapes may differ from level set
1434       // * solution tape may have native format (like Supaplex solution files)
1435
1436       SaveScoreTape(level_nr);
1437       SaveServerScore(level_nr);
1438
1439       AutoPlayTapes_WaitForUpload();
1440     }
1441
1442     if (patch_nr == 0)
1443       autoplay.num_levels_played++;
1444
1445     if (tape.auto_play_level_solved)
1446       autoplay.num_levels_solved++;
1447
1448     if (level_nr >= 0 && level_nr < MAX_TAPES_PER_SET)
1449       autoplay.level_failed[level_nr] = !tape.auto_play_level_solved;
1450   }
1451   else
1452   {
1453     if ((global.autoplay_mode == AUTOPLAY_MODE_SAVE ||
1454          global.autoplay_mode == AUTOPLAY_MODE_UPLOAD) &&
1455         !options.mytapes &&
1456         options.player_name == NULL)
1457     {
1458       Fail("specify player name when uploading solution tapes");
1459     }
1460
1461     DrawCompleteVideoDisplay();
1462
1463     audio.sound_enabled = FALSE;
1464     setup.engine_snapshot_mode = getStringCopy(STR_SNAPSHOT_MODE_OFF);
1465
1466     if (strSuffix(global.autoplay_leveldir, ".tape"))
1467     {
1468       autoplay.tape_filename = global.autoplay_leveldir;
1469
1470       LoadTapeFromFilename(autoplay.tape_filename);
1471
1472       if (tape.no_valid_file)
1473       {
1474         if (!fileExists(autoplay.tape_filename))
1475           Fail("tape file '%s' does not exist", autoplay.tape_filename);
1476         else
1477           Fail("cannot load tape file '%s'", autoplay.tape_filename);
1478       }
1479
1480       global.autoplay_leveldir = tape.level_identifier;
1481
1482       if (tape.level_nr >= 0 && tape.level_nr < MAX_TAPES_PER_SET)
1483         global.autoplay_level[tape.level_nr] = TRUE;
1484
1485       global.autoplay_all = FALSE;
1486     }
1487
1488     autoplay.leveldir = getTreeInfoFromIdentifier(leveldir_first,
1489                                                   global.autoplay_leveldir);
1490
1491     if (autoplay.leveldir == NULL)
1492       Fail("no such level identifier: '%s'", global.autoplay_leveldir);
1493
1494     leveldir_current = autoplay.leveldir;
1495
1496     if (autoplay.leveldir->first_level < 0)
1497       autoplay.leveldir->first_level = 0;
1498     if (autoplay.leveldir->last_level >= MAX_TAPES_PER_SET)
1499       autoplay.leveldir->last_level = MAX_TAPES_PER_SET - 1;
1500
1501     autoplay.level_nr = autoplay.leveldir->first_level;
1502
1503     PrintLine("=", 79);
1504     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1505       Print("Automatically fixing level tapes\n");
1506     else if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1507       Print("Automatically uploading level tapes\n");
1508     else
1509       Print("Automatically playing level tapes\n");
1510     PrintLine("-", 79);
1511     Print("Level series identifier: '%s'\n", autoplay.leveldir->identifier);
1512     Print("Level series name:       '%s'\n", autoplay.leveldir->name);
1513     Print("Level series author:     '%s'\n", autoplay.leveldir->author);
1514     Print("Number of levels:        %d\n",   autoplay.leveldir->levels);
1515     PrintLine("=", 79);
1516     Print("\n");
1517
1518     for (i = 0; i < MAX_TAPES_PER_SET; i++)
1519       autoplay.level_failed[i] = FALSE;
1520
1521     // only private tapes may be modified
1522     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1523       options.mytapes = TRUE;
1524
1525     autoplay.initialized = TRUE;
1526   }
1527
1528   while (1)
1529   {
1530     if (global.autoplay_mode != AUTOPLAY_MODE_FIX || patch_nr == 0)
1531       level_nr = autoplay.level_nr++;
1532
1533     if (level_nr > autoplay.leveldir->last_level)
1534       break;
1535
1536     // set patch info (required for progress output)
1537     strcpy(tape_patch_info, "");
1538     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1539       snprintf(tape_patch_info, MAX_OUTPUT_LINESIZE, "[%-13s] ",
1540                patch_name[patch_nr]);
1541
1542     if (!global.autoplay_all && !global.autoplay_level[level_nr])
1543       continue;
1544
1545     TapeErase();
1546
1547     LoadLevel(level_nr);
1548
1549     if (level.no_level_file || level.no_valid_file)
1550     {
1551       Print("Tape %03d: (no level found)\n", level_nr);
1552
1553       continue;
1554     }
1555
1556 #if 0
1557     // ACTIVATE THIS FOR LOADING/TESTING OF LEVELS ONLY
1558     Print("Tape %03d: (only testing level)\n", level_nr);
1559     continue;
1560 #endif
1561
1562     if (autoplay.tape_filename)
1563       LoadTapeFromFilename(autoplay.tape_filename);
1564     else if (options.mytapes)
1565       LoadTape(level_nr);
1566     else
1567       LoadSolutionTape(level_nr);
1568
1569     if (tape.no_valid_file)
1570     {
1571       autoplay.num_tape_missing++;
1572
1573       Print("Tape %03d: (no tape found)\n", level_nr);
1574
1575       continue;
1576     }
1577
1578     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1579     {
1580       boolean skip_patch = FALSE;
1581
1582       if (tape.engine_version < patch_version_first[patch_nr] ||
1583           tape.engine_version > patch_version_last[patch_nr])
1584       {
1585         Print("Tape %03d %s[%02d:%02d]: (%s %d.%d.%d.%d) - skipped.\n",
1586               level_nr,  tape_patch_info,
1587               tape.length_seconds / 60, tape.length_seconds % 60,
1588               "not suitable for version",
1589               (tape.engine_version / 1000000) % 100,
1590               (tape.engine_version / 10000  ) % 100,
1591               (tape.engine_version / 100    ) % 100,
1592               (tape.engine_version          ) % 100);
1593
1594         skip_patch = TRUE;
1595       }
1596
1597       if (strEqual(patch_name[patch_nr], "screen_34x34") &&
1598           tape.num_participating_players == 1)
1599       {
1600         Print("Tape %03d %s[%02d:%02d]: (%s) - skipped.\n",
1601               level_nr,  tape_patch_info,
1602               tape.length_seconds / 60, tape.length_seconds % 60,
1603               "not suitable for single player tapes");
1604
1605         skip_patch = TRUE;
1606       }
1607
1608       if (skip_patch)
1609       {
1610         if (patch_name[patch_nr + 1] != NULL)
1611         {
1612           // continue with next patch
1613           patch_nr++;
1614         }
1615         else
1616         {
1617           // continue with next tape
1618           patch_nr = 0;
1619         }
1620
1621         continue;
1622       }
1623
1624       if (strEqual(patch_name[patch_nr], "screen_34x34"))
1625       {
1626         tape.scr_fieldx = SCR_FIELDX_DEFAULT * 2;
1627         tape.scr_fieldy = SCR_FIELDY_DEFAULT * 2;
1628       }
1629       else
1630       {
1631         tape.property_bits |= patch_property_bit[patch_nr];
1632       }
1633     }
1634
1635     if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1636     {
1637       boolean use_temporary_tape_file = FALSE;
1638
1639       Print("Tape %03d:\n", level_nr);
1640
1641       AutoPlayTapes_SetScoreEntry(0, 0);
1642
1643       if (autoplay.tape_filename == NULL)
1644       {
1645         autoplay.tape_filename = (options.mytapes ? getTapeFilename(level_nr) :
1646                                   getDefaultSolutionTapeFilename(level_nr));
1647
1648         if (!fileExists(autoplay.tape_filename))
1649         {
1650           // non-standard solution tape -- save to temporary file
1651           autoplay.tape_filename = getTemporaryTapeFilename();
1652
1653           SaveTapeToFilename(autoplay.tape_filename);
1654
1655           use_temporary_tape_file = TRUE;
1656         }
1657       }
1658
1659       SaveServerScoreFromFile(level_nr, autoplay.tape_filename);
1660
1661       AutoPlayTapes_WaitForUpload();
1662
1663       if (use_temporary_tape_file)
1664         unlink(autoplay.tape_filename);
1665
1666       // required for uploading multiple tapes
1667       autoplay.tape_filename = NULL;
1668
1669       continue;
1670     }
1671
1672     InitCounter();
1673
1674     if (options.tape_log_filename != NULL)
1675       OpenTapeLogfile();
1676
1677     TapeStartGamePlaying();
1678     TapeStartWarpForward(global.autoplay_mode);
1679
1680     autoplay.last_level_nr = level_nr;
1681
1682     return;
1683   }
1684
1685   char *autoplay_status =
1686     (autoplay.num_levels_played == autoplay.num_levels_solved &&
1687      autoplay.num_levels_played > 0 ? " OK " : "WARN");
1688   int autoplay_percent =
1689     (autoplay.num_levels_played ?
1690      autoplay.num_levels_solved * 100 / autoplay.num_levels_played : 0);
1691
1692   Print("\n");
1693   PrintLine("=", 79);
1694   Print("Number of levels played: %d\n", autoplay.num_levels_played);
1695   Print("Number of levels solved: %d (%d%%)\n", autoplay.num_levels_solved,
1696         (autoplay.num_levels_played ?
1697          autoplay.num_levels_solved * 100 / autoplay.num_levels_played : 0));
1698   if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1699     Print("Number of tapes fixed: %d\n", autoplay.num_tapes_patched);
1700   PrintLine("-", 79);
1701   Print("Summary (for automatic parsing by scripts):\n");
1702
1703   if (autoplay.tape_filename)
1704   {
1705     Print("TAPEFILE [%s] '%s', %d, %d, %d",
1706           autoplay_status,
1707           autoplay.leveldir->identifier,
1708           autoplay.last_level_nr,
1709           game.score_final,
1710           game.score_time_final);
1711   }
1712   else
1713   {
1714     Print("LEVELDIR [%s] '%s', SOLVED %d/%d (%d%%)",
1715           autoplay_status,
1716           autoplay.leveldir->identifier,
1717           autoplay.num_levels_solved,
1718           autoplay.num_levels_played,
1719           autoplay_percent);
1720
1721     if (autoplay.num_levels_played != autoplay.num_levels_solved)
1722     {
1723       Print(", FAILED:");
1724       for (i = 0; i < MAX_TAPES_PER_SET; i++)
1725         if (autoplay.level_failed[i])
1726           Print(" %03d", i);
1727     }
1728   }
1729
1730   Print("\n");
1731   PrintLine("=", 79);
1732
1733   CloseAllAndExit(0);
1734 }
1735
1736
1737 // ----------------------------------------------------------------------------
1738 // tape patch functions
1739 // ----------------------------------------------------------------------------
1740
1741 static boolean PatchTape(struct TapeInfo *tape, char *mode)
1742 {
1743   Print("[%d.%d.%d.%d]: ",
1744         (tape->engine_version / 1000000) % 100,
1745         (tape->engine_version / 10000  ) % 100,
1746         (tape->engine_version / 100    ) % 100,
1747         (tape->engine_version          ) % 100);
1748
1749   if (strEqual(mode, "info"))
1750   {
1751     Print("property bits == 0x%02x\n", tape->property_bits);
1752
1753     return FALSE;
1754   }
1755
1756   boolean unpatch_tape = FALSE;
1757   boolean use_property_bit = FALSE;
1758   byte property_bitmask = 0;
1759
1760   if (strSuffix(mode, ":0") ||
1761       strSuffix(mode, ":off") ||
1762       strSuffix(mode, ":clear"))
1763     unpatch_tape = TRUE;
1764
1765   if (strEqual(mode, "em_random_bug") || strPrefix(mode, "em_random_bug:"))
1766   {
1767     // this bug was introduced in version 3.3.1.0 and fixed in version 4.0.1.2
1768     if (tape->engine_version <  VERSION_IDENT(3,3,1,0) ||
1769         tape->engine_version >= VERSION_IDENT(4,0,1,2))
1770     {
1771       Print("This tape version cannot be patched against EM random bug!\n");
1772
1773       return FALSE;
1774     }
1775
1776     property_bitmask = TAPE_PROPERTY_EM_RANDOM_BUG;
1777
1778     use_property_bit = TRUE;
1779   }
1780   else if (strEqual(mode, "screen_34x34") || strPrefix(mode, "screen_34x34:"))
1781   {
1782     // this bug only affects team mode tapes
1783     if (tape->num_participating_players == 1)
1784     {
1785       Print("Only team mode tapes can be patched against screen size bug!\n");
1786
1787       return FALSE;
1788     }
1789
1790     // this bug (that always existed before) was fixed in version 4.2.2.1
1791     if (tape->engine_version >= VERSION_IDENT(4,2,2,1))
1792     {
1793       Print("This tape version cannot be patched against screen size bug!\n");
1794
1795       return FALSE;
1796     }
1797
1798     int factor = (unpatch_tape ? 1 : 2);
1799     int scr_fieldx_new = SCR_FIELDX_DEFAULT * factor;
1800     int scr_fieldy_new = SCR_FIELDY_DEFAULT * factor;
1801
1802     if (scr_fieldx_new == tape->scr_fieldx &&
1803         scr_fieldy_new == tape->scr_fieldy)
1804     {
1805       Print("Tape already patched for '%s'!\n", mode);
1806
1807       return FALSE;
1808     }
1809
1810     tape->scr_fieldx = scr_fieldx_new;
1811     tape->scr_fieldy = scr_fieldy_new;
1812   }
1813   else
1814   {
1815     Print("Unknown patch mode '%s'!\n", mode);
1816
1817     return FALSE;
1818   }
1819
1820   // patching tapes using property bits may be used for several patch modes
1821   if (use_property_bit)
1822   {
1823     byte property_bits = tape->property_bits;
1824     boolean set_property_bit = (unpatch_tape ? FALSE : TRUE);
1825
1826     if (set_property_bit)
1827       property_bits |= property_bitmask;
1828     else
1829       property_bits &= ~property_bitmask;
1830
1831     if (property_bits == tape->property_bits)
1832     {
1833       Print("Tape already patched for '%s'!\n", mode);
1834
1835       return FALSE;
1836     }
1837
1838     tape->property_bits = property_bits;
1839   }
1840
1841   Print("Patching for '%s' ... ", mode);
1842
1843   return TRUE;
1844 }
1845
1846 void PatchTapes(void)
1847 {
1848   static LevelDirTree *patchtapes_leveldir = NULL;
1849   static int num_tapes_found = 0;
1850   static int num_tapes_patched = 0;
1851   char *mode = global.patchtapes_mode;
1852   int i;
1853
1854   if (strEqual(mode, "help"))
1855   {
1856     PrintLine("=", 79);
1857     Print("Supported patch modes:\n");
1858     Print("- \"em_random_bug\"   - use 64-bit random value bug for EM engine\n");
1859     Print("- \"screen_34x34\"    - force visible playfield size of 34 x 34\n");
1860     PrintLine("-", 79);
1861     Print("Supported modifiers:\n");
1862     Print("- add \":0\", \":off\" or \":clear\" to patch mode to un-patch tape file\n");
1863     PrintLine("=", 79);
1864
1865     CloseAllAndExit(0);
1866   }
1867
1868   patchtapes_leveldir = getTreeInfoFromIdentifier(leveldir_first,
1869                                                   global.patchtapes_leveldir);
1870
1871   if (patchtapes_leveldir == NULL)
1872     Fail("no such level identifier: '%s'", global.patchtapes_leveldir);
1873
1874   leveldir_current = patchtapes_leveldir;
1875
1876   if (patchtapes_leveldir->first_level < 0)
1877     patchtapes_leveldir->first_level = 0;
1878   if (patchtapes_leveldir->last_level >= MAX_TAPES_PER_SET)
1879     patchtapes_leveldir->last_level = MAX_TAPES_PER_SET - 1;
1880
1881   PrintLine("=", 79);
1882   Print("Patching level tapes for patch mode '%s'\n", mode);
1883   PrintLine("-", 79);
1884   Print("Level series identifier: '%s'\n", patchtapes_leveldir->identifier);
1885   Print("Level series name:       '%s'\n", patchtapes_leveldir->name);
1886   Print("Level series author:     '%s'\n", patchtapes_leveldir->author);
1887   Print("Number of levels:        %d\n",   patchtapes_leveldir->levels);
1888   PrintLine("=", 79);
1889   Print("\n");
1890
1891   int first_level = patchtapes_leveldir->first_level;
1892   int last_level = patchtapes_leveldir->last_level;
1893
1894   for (i = first_level; i <= last_level; i++)
1895   {
1896     if (!global.patchtapes_all && !global.patchtapes_level[i])
1897       continue;
1898
1899     Print("Tape %03d: ", i);
1900
1901     TapeErase();
1902     LoadTape(i);
1903
1904     if (tape.no_valid_file)
1905     {
1906       Print("(no tape found)\n");
1907
1908       continue;
1909     }
1910
1911     num_tapes_found++;
1912
1913     if (PatchTape(&tape, mode))
1914     {
1915       char *filename = getTapeFilename(i);
1916       char *filename_orig = getStringCat2(filename, ".orig");
1917
1918       if (!fileExists(filename_orig))
1919         rename(filename, filename_orig);
1920
1921       SaveTapeToFilename(filename);
1922
1923       Print("patched tape saved.\n");
1924
1925       num_tapes_patched++;
1926     }
1927   }
1928
1929   Print("\n");
1930   PrintLine("=", 79);
1931   Print("Number of tapes found: %d\n", num_tapes_found);
1932   Print("Number of tapes patched: %d\n", num_tapes_patched);
1933   PrintLine("=", 79);
1934
1935   CloseAllAndExit(0);
1936 }
1937
1938
1939 // ---------- new tape button stuff -------------------------------------------
1940
1941 static struct
1942 {
1943   int graphic;
1944   struct XY *pos;
1945   int gadget_id;
1946   char *infotext;
1947 } tapebutton_info[NUM_TAPE_BUTTONS] =
1948 {
1949   {
1950     IMG_GFX_TAPE_BUTTON_EJECT,          &tape.button.eject,
1951     TAPE_CTRL_ID_EJECT,                 "eject tape"
1952   },
1953   {
1954     // (same position as "eject" button)
1955     IMG_GFX_TAPE_BUTTON_EXTRA,          &tape.button.eject,
1956     TAPE_CTRL_ID_EXTRA,                 "extra functions"
1957   },
1958   {
1959     IMG_GFX_TAPE_BUTTON_STOP,           &tape.button.stop,
1960     TAPE_CTRL_ID_STOP,                  "stop tape"
1961   },
1962   {
1963     IMG_GFX_TAPE_BUTTON_PAUSE,          &tape.button.pause,
1964     TAPE_CTRL_ID_PAUSE,                 "pause tape"
1965   },
1966   {
1967     IMG_GFX_TAPE_BUTTON_RECORD,         &tape.button.record,
1968     TAPE_CTRL_ID_RECORD,                "record tape"
1969   },
1970   {
1971     IMG_GFX_TAPE_BUTTON_PLAY,           &tape.button.play,
1972     TAPE_CTRL_ID_PLAY,                  "play tape"
1973   },
1974   {
1975     IMG_GFX_TAPE_BUTTON_INSERT_SOLUTION,&tape.button.insert_solution,
1976     TAPE_CTRL_ID_INSERT_SOLUTION,       "insert solution tape"
1977   },
1978   {
1979     IMG_GFX_TAPE_BUTTON_PLAY_SOLUTION,  &tape.button.play_solution,
1980     TAPE_CTRL_ID_PLAY_SOLUTION,         "play solution tape"
1981   }
1982 };
1983
1984 void CreateTapeButtons(void)
1985 {
1986   int i;
1987
1988   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1989   {
1990     int graphic = tapebutton_info[i].graphic;
1991     struct GraphicInfo *gfx = &graphic_info[graphic];
1992     struct XY *pos = tapebutton_info[i].pos;
1993     struct GadgetInfo *gi;
1994     int gd_x = gfx->src_x;
1995     int gd_y = gfx->src_y;
1996     int gd_xp = gfx->src_x + gfx->pressed_xoffset;
1997     int gd_yp = gfx->src_y + gfx->pressed_yoffset;
1998     int id = i;
1999
2000     gi = CreateGadget(GDI_CUSTOM_ID, id,
2001                       GDI_IMAGE_ID, graphic,
2002                       GDI_INFO_TEXT, tapebutton_info[i].infotext,
2003                       GDI_X, VX + pos->x,
2004                       GDI_Y, VY + pos->y,
2005                       GDI_WIDTH, gfx->width,
2006                       GDI_HEIGHT, gfx->height,
2007                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
2008                       GDI_STATE, GD_BUTTON_UNPRESSED,
2009                       GDI_DESIGN_UNPRESSED, gfx->bitmap, gd_x, gd_y,
2010                       GDI_DESIGN_PRESSED, gfx->bitmap, gd_xp, gd_yp,
2011                       GDI_DIRECT_DRAW, FALSE,
2012                       GDI_EVENT_MASK, GD_EVENT_RELEASED,
2013                       GDI_CALLBACK_ACTION, HandleTapeButtons,
2014                       GDI_END);
2015
2016     if (gi == NULL)
2017       Fail("cannot create gadget");
2018
2019     tape_gadget[id] = gi;
2020   }
2021 }
2022
2023 void FreeTapeButtons(void)
2024 {
2025   int i;
2026
2027   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2028     FreeGadget(tape_gadget[i]);
2029 }
2030
2031 void MapTapeEjectButton(void)
2032 {
2033   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
2034   MapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
2035 }
2036
2037 void MapTapeWarpButton(void)
2038 {
2039   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
2040   MapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
2041 }
2042
2043 void MapTapeButtons(void)
2044 {
2045   int i;
2046
2047   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2048     if (i != TAPE_CTRL_ID_EXTRA)
2049       MapGadget(tape_gadget[i]);
2050
2051   if (tape.recording || tape.playing)
2052     MapTapeWarpButton();
2053
2054   if (tape.show_game_buttons)
2055     MapGameButtonsOnTape();
2056 }
2057
2058 void UnmapTapeButtons(void)
2059 {
2060   int i;
2061
2062   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2063     UnmapGadget(tape_gadget[i]);
2064
2065   if (tape.show_game_buttons)
2066     UnmapGameButtonsOnTape();
2067 }
2068
2069 void RedrawTapeButtons(void)
2070 {
2071   int i;
2072
2073   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2074     RedrawGadget(tape_gadget[i]);
2075
2076   if (tape.show_game_buttons)
2077     RedrawGameButtonsOnTape();
2078 }
2079
2080 void RedrawOrRemapTapeButtons(void)
2081 {
2082   if (tape_gadget[TAPE_CTRL_ID_PLAY]->mapped)
2083   {
2084     // tape buttons already mapped
2085     RedrawTapeButtons();
2086   }
2087   else
2088   {
2089     UnmapTapeButtons();
2090     MapTapeButtons();
2091   }
2092 }
2093
2094 static void HandleTapeButtonsExt(int id)
2095 {
2096   if (game_status != GAME_MODE_MAIN && game_status != GAME_MODE_PLAYING)
2097     return;
2098
2099   switch (id)
2100   {
2101     case TAPE_CTRL_ID_EJECT:
2102       TapeStop();
2103
2104       if (TAPE_IS_EMPTY(tape))
2105       {
2106         LoadTape(level_nr);
2107
2108         if (TAPE_IS_EMPTY(tape))
2109           Request("No tape for this level!", REQ_CONFIRM);
2110       }
2111       else
2112       {
2113         if (tape.changed)
2114           SaveTapeChecked(level_nr);
2115
2116         TapeErase();
2117       }
2118
2119       DrawCompleteVideoDisplay();
2120       break;
2121
2122     case TAPE_CTRL_ID_EXTRA:
2123       if (tape.playing)
2124       {
2125         tape.pause_before_end = !tape.pause_before_end;
2126
2127         DrawVideoDisplayCurrentState();
2128       }
2129       else if (tape.recording)
2130       {
2131         TapeSingleStep();
2132       }
2133
2134       break;
2135
2136     case TAPE_CTRL_ID_STOP:
2137       TapeStop();
2138
2139       break;
2140
2141     case TAPE_CTRL_ID_PAUSE:
2142       TapeTogglePause(TAPE_TOGGLE_MANUAL);
2143
2144       break;
2145
2146     case TAPE_CTRL_ID_RECORD:
2147       if (TAPE_IS_STOPPED(tape))
2148       {
2149         TapeStartGameRecording();
2150       }
2151       else if (tape.pausing)
2152       {
2153         if (tape.playing)                       // PLAY -> PAUSE -> RECORD
2154           TapeAppendRecording();
2155         else
2156           TapeTogglePause(TAPE_TOGGLE_MANUAL);
2157       }
2158
2159       break;
2160
2161     case TAPE_CTRL_ID_PLAY:
2162       if (tape.recording && tape.pausing)       // PAUSE -> RECORD
2163       {
2164         // ("TAPE_IS_EMPTY(tape)" is TRUE here -- probably fix this)
2165
2166         TapeTogglePause(TAPE_TOGGLE_MANUAL);
2167       }
2168
2169       if (TAPE_IS_EMPTY(tape))
2170         break;
2171
2172       if (TAPE_IS_STOPPED(tape))
2173       {
2174         TapeStartGamePlaying();
2175       }
2176       else if (tape.playing)
2177       {
2178         if (tape.pausing)                       // PAUSE -> PLAY
2179         {
2180           TapeTogglePause(TAPE_TOGGLE_MANUAL | TAPE_TOGGLE_PLAY_PAUSE);
2181         }
2182         else if (!tape.fast_forward)            // PLAY -> FFWD
2183         {
2184           tape.fast_forward = TRUE;
2185         }
2186         else if (!tape.warp_forward)            // FFWD -> WARP
2187         {
2188           tape.warp_forward = TRUE;
2189         }
2190         else if (!tape.deactivate_display)      // WARP -> WARP BLIND
2191         {
2192           tape.deactivate_display = TRUE;
2193
2194           TapeDeactivateDisplayOn();
2195         }
2196         else                                    // WARP BLIND -> PLAY
2197         {
2198           tape.fast_forward = FALSE;
2199           tape.warp_forward = FALSE;
2200           tape.deactivate_display = FALSE;
2201
2202           TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
2203         }
2204
2205         DrawVideoDisplayCurrentState();
2206       }
2207
2208       break;
2209
2210     case TAPE_CTRL_ID_INSERT_SOLUTION:
2211       InsertSolutionTape();
2212
2213       break;
2214
2215     case TAPE_CTRL_ID_PLAY_SOLUTION:
2216       PlaySolutionTape();
2217
2218       break;
2219
2220     default:
2221       break;
2222   }
2223 }
2224
2225 static void HandleTapeButtons(struct GadgetInfo *gi)
2226 {
2227   HandleTapeButtonsExt(gi->custom_id);
2228 }
2229
2230 void HandleTapeButtonKeys(Key key)
2231 {
2232   boolean eject_button_is_active = TAPE_IS_STOPPED(tape);
2233   boolean extra_button_is_active = !eject_button_is_active;
2234
2235   if (key == setup.shortcut.tape_eject && eject_button_is_active)
2236     HandleTapeButtonsExt(TAPE_CTRL_ID_EJECT);
2237   else if (key == setup.shortcut.tape_extra && extra_button_is_active)
2238     HandleTapeButtonsExt(TAPE_CTRL_ID_EXTRA);
2239   else if (key == setup.shortcut.tape_stop)
2240     HandleTapeButtonsExt(TAPE_CTRL_ID_STOP);
2241   else if (key == setup.shortcut.tape_pause)
2242     HandleTapeButtonsExt(TAPE_CTRL_ID_PAUSE);
2243   else if (key == setup.shortcut.tape_record)
2244     HandleTapeButtonsExt(TAPE_CTRL_ID_RECORD);
2245   else if (key == setup.shortcut.tape_play)
2246     HandleTapeButtonsExt(TAPE_CTRL_ID_PLAY);
2247 }