added saving non-standard solution tape to temporary file before uploading
[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 static char tape_patch_info[MAX_OUTPUT_LINESIZE];
475
476 static void PrintTapeReplayProgress(boolean replay_finished)
477 {
478   static unsigned int counter_last = -1;
479   unsigned int counter = Counter();
480   unsigned int counter_seconds  = counter / 1000;
481
482   if (!replay_finished)
483   {
484     unsigned int counter_delay = 50;
485
486     if (counter > counter_last + counter_delay)
487     {
488       PrintNoLog("\r");
489       PrintNoLog("Tape %03d %s[%02d:%02d]: [%02d:%02d] - playing tape ... ",
490                  level_nr,  tape_patch_info,
491                  tape.length_seconds / 60, tape.length_seconds % 60,
492                  TapeTime / 60, TapeTime % 60);
493
494       counter_last = counter;
495     }
496   }
497   else
498   {
499     float tape_length_seconds = GetTapeLengthSecondsFloat();
500
501     PrintNoLog("\r");
502     Print("Tape %03d %s[%02d:%02d]: (%02d:%02d.%03d / %.2f %%) - %s.\n",
503           level_nr, tape_patch_info,
504           tape.length_seconds / 60, tape.length_seconds % 60,
505           counter_seconds / 60, counter_seconds % 60, counter % 1000,
506           (float)counter / tape_length_seconds / 10,
507           tape.auto_play_level_fixed ? "solved and fixed" :
508           tape.auto_play_level_solved ? "solved" :
509           tape.auto_play_level_not_fixable ? "NOT SOLVED, NOT FIXED" :
510           "NOT SOLVED");
511
512     counter_last = -1;
513   }
514 }
515
516 static FILE *tape_log_file;
517
518 static void OpenTapeLogfile(void)
519 {
520   if (!(tape_log_file = fopen(options.tape_log_filename, MODE_WRITE)))
521     Warn("cannot write tape logfile '%s'", options.tape_log_filename);
522 }
523
524 static void WriteTapeLogfile(byte action[MAX_TAPE_ACTIONS])
525 {
526   int i;
527
528   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
529     putFile8Bit(tape_log_file, action[i]);
530 }
531
532 static void CloseTapeLogfile(void)
533 {
534   fclose(tape_log_file);
535 }
536
537
538 // ============================================================================
539 // tape control functions
540 // ============================================================================
541
542 void TapeSetDateFromEpochSeconds(time_t epoch_seconds)
543 {
544   struct tm *lt = localtime(&epoch_seconds);
545
546   tape.date = 10000 * (lt->tm_year % 100) + 100 * lt->tm_mon + lt->tm_mday;
547 }
548
549 void TapeSetDateFromNow(void)
550 {
551   TapeSetDateFromEpochSeconds(time(NULL));
552 }
553
554 void TapeErase(void)
555 {
556   int i;
557
558   CopyTapeToUndoBuffer();
559
560   tape.counter = 0;
561   tape.length = 0;
562   tape.length_frames = 0;
563   tape.length_seconds = 0;
564
565   tape.score_tape_basename[0] = '\0';
566
567   if (leveldir_current)
568   {
569     strncpy(tape.level_identifier, leveldir_current->identifier,
570             MAX_FILENAME_LEN);
571     tape.level_identifier[MAX_FILENAME_LEN] = '\0';
572   }
573
574   tape.level_nr = level_nr;
575   tape.pos[tape.counter].delay = 0;
576   tape.changed = TRUE;
577
578   tape.random_seed = InitRND(level.random_seed);
579
580   tape.file_version = FILE_VERSION_ACTUAL;
581   tape.game_version = GAME_VERSION_ACTUAL;
582   tape.engine_version = level.game_version;
583
584   tape.property_bits = TAPE_PROPERTY_NONE;
585
586   TapeSetDateFromNow();
587
588   for (i = 0; i < MAX_PLAYERS; i++)
589     tape.player_participates[i] = FALSE;
590
591   tape.centered_player_nr_next = -1;
592   tape.set_centered_player = FALSE;
593
594   // set flags for game actions to default values (may be overwritten later)
595   tape.use_key_actions = TRUE;
596   tape.use_mouse_actions = FALSE;
597 }
598
599 static void TapeRewind(void)
600 {
601   tape.counter = 0;
602   tape.delay_played = 0;
603   tape.pause_before_end = FALSE;
604   tape.recording = FALSE;
605   tape.playing = FALSE;
606   tape.fast_forward = FALSE;
607   tape.warp_forward = FALSE;
608   tape.deactivate_display = FALSE;
609   tape.auto_play = (global.autoplay_leveldir != NULL);
610   tape.auto_play_level_solved = FALSE;
611   tape.auto_play_level_fixed = FALSE;
612   tape.auto_play_level_not_fixable = FALSE;
613   tape.quick_resume = FALSE;
614   tape.single_step = FALSE;
615
616   tape.centered_player_nr_next = -1;
617   tape.set_centered_player = FALSE;
618
619   InitRND(tape.random_seed);
620 }
621
622 static void TapeSetRandomSeed(int random_seed)
623 {
624   tape.random_seed = InitRND(random_seed);
625 }
626
627 void TapeStartRecording(int random_seed)
628 {
629   if (!TAPE_IS_STOPPED(tape))
630     TapeStop();
631
632   TapeErase();
633   TapeRewind();
634   TapeSetRandomSeed(random_seed);
635
636   tape.recording = TRUE;
637
638   DrawVideoDisplay(VIDEO_STATE_REC_ON, 0);
639   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
640   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
641   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
642
643   MapTapeWarpButton();
644
645   SetDrawDeactivationMask(REDRAW_NONE);
646   audio.sound_deactivated = FALSE;
647
648   // required here to update video display if tape door is closed
649   if (GetDoorState() & DOOR_CLOSE_2)
650     OpenDoor(GetDoorState() | DOOR_NO_DELAY | DOOR_FORCE_REDRAW);
651 }
652
653 static void TapeStartGameRecording(void)
654 {
655   StartGameActions(network.enabled, TRUE, level.random_seed);
656 }
657
658 static void TapeAppendRecording(void)
659 {
660   if (!tape.playing || !tape.pausing)
661     return;
662
663   // stop playing
664   tape.playing = FALSE;
665   tape.fast_forward = FALSE;
666   tape.warp_forward = FALSE;
667   tape.pause_before_end = FALSE;
668   tape.deactivate_display = FALSE;
669
670   // start recording
671   tape.recording = TRUE;
672   tape.changed = TRUE;
673
674   // set current delay (for last played move)
675   tape.pos[tape.counter].delay = tape.delay_played;
676
677   tape.property_bits |= TAPE_PROPERTY_REPLAYED;
678
679   // set current date
680   TapeSetDateFromNow();
681
682   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
683   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF | VIDEO_STATE_REC_ON, 0);
684
685   UpdateAndDisplayGameControlValues();
686 }
687
688 void TapeHaltRecording(void)
689 {
690   tape.counter++;
691
692   // initialize delay for next tape entry (to be able to continue recording)
693   if (tape.counter < MAX_TAPE_LEN)
694     tape.pos[tape.counter].delay = 0;
695
696   tape.length = tape.counter;
697   tape.length_frames = GetTapeLengthFrames();
698   tape.length_seconds = GetTapeLengthSeconds();
699 }
700
701 void TapeStopRecording(void)
702 {
703   if (tape.recording)
704     TapeHaltRecording();
705
706   tape.recording = FALSE;
707   tape.pausing = FALSE;
708
709   DrawVideoDisplay(VIDEO_STATE_REC_OFF, 0);
710   MapTapeEjectButton();
711 }
712
713 boolean TapeAddAction(byte action[MAX_TAPE_ACTIONS])
714 {
715   int i;
716
717   if (tape.pos[tape.counter].delay > 0)         // already stored action
718   {
719     boolean changed_events = FALSE;
720
721     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
722       if (tape.pos[tape.counter].action[i] != action[i])
723         changed_events = TRUE;
724
725     if (changed_events || tape.pos[tape.counter].delay >= 255)
726     {
727       if (tape.counter >= MAX_TAPE_LEN - 1)
728         return FALSE;
729
730       tape.counter++;
731       tape.pos[tape.counter].delay = 0;
732     }
733     else
734       tape.pos[tape.counter].delay++;
735   }
736
737   if (tape.pos[tape.counter].delay == 0)        // store new action
738   {
739     for (i = 0; i < MAX_TAPE_ACTIONS; i++)
740       tape.pos[tape.counter].action[i] = action[i];
741
742     tape.pos[tape.counter].delay++;
743   }
744
745   return TRUE;
746 }
747
748 void TapeRecordAction(byte action_raw[MAX_TAPE_ACTIONS])
749 {
750   byte action[MAX_TAPE_ACTIONS];
751   int i;
752
753   if (!tape.recording)          // (record action even when tape is paused)
754     return;
755
756   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
757     action[i] = action_raw[i];
758
759   if (tape.use_key_actions && tape.set_centered_player)
760   {
761     for (i = 0; i < MAX_PLAYERS; i++)
762       if (tape.centered_player_nr_next == i ||
763           tape.centered_player_nr_next == -1)
764         action[i] |= KEY_SET_FOCUS;
765
766     tape.set_centered_player = FALSE;
767   }
768
769   if (GameFrameDelay != GAME_FRAME_DELAY)
770     tape.property_bits |= TAPE_PROPERTY_GAME_SPEED;
771
772   if (setup.small_game_graphics || SCR_FIELDX >= 2 * SCR_FIELDX_DEFAULT)
773     tape.property_bits |= TAPE_PROPERTY_SMALL_GRAPHICS;
774
775   if (!TapeAddAction(action))
776     TapeStopRecording();
777 }
778
779 void TapeTogglePause(boolean toggle_mode)
780 {
781   if (tape.playing && tape.pausing && (toggle_mode & TAPE_TOGGLE_PLAY_PAUSE))
782   {
783     // continue playing in normal mode
784     tape.fast_forward = FALSE;
785     tape.warp_forward = FALSE;
786     tape.deactivate_display = FALSE;
787
788     tape.pause_before_end = FALSE;
789   }
790
791   tape.pausing = !tape.pausing;
792
793   if (tape.single_step && (toggle_mode & TAPE_TOGGLE_MANUAL))
794     tape.single_step = FALSE;
795
796   if (tape.single_step)
797     tape.property_bits |= TAPE_PROPERTY_SINGLE_STEP;
798
799   if (tape.pausing)
800     tape.property_bits |= TAPE_PROPERTY_PAUSE_MODE;
801
802   DrawVideoDisplayCurrentState();
803
804   if (tape.deactivate_display)
805   {
806     if (tape.pausing)
807       TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
808     else
809       TapeDeactivateDisplayOn();
810   }
811
812   if (tape.quick_resume)
813   {
814     tape.quick_resume = FALSE;
815
816     TapeStopWarpForward();
817     TapeAppendRecording();
818
819     if (!CheckEngineSnapshotSingle())
820       SaveEngineSnapshotSingle();
821
822     // restart step/move snapshots after quick loading tape
823     SaveEngineSnapshotToListInitial();
824
825     // do not map undo/redo buttons after quick loading tape
826     return;
827   }
828
829   if (game_status == GAME_MODE_PLAYING)
830   {
831     if (setup.show_load_save_buttons &&
832         setup.show_undo_redo_buttons &&
833         CheckEngineSnapshotList())
834     {
835       if (tape.pausing)
836         MapUndoRedoButtons();
837       else if (!tape.single_step)
838         MapLoadSaveButtons();
839     }
840
841     ModifyPauseButtons();
842   }
843 }
844
845 void TapeStartPlaying(void)
846 {
847   if (TAPE_IS_EMPTY(tape))
848     return;
849
850   if (!TAPE_IS_STOPPED(tape))
851     TapeStop();
852
853   TapeRewind();
854
855   tape.playing = TRUE;
856
857   DrawVideoDisplay(VIDEO_STATE_PLAY_ON, 0);
858   DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
859   DrawVideoDisplay(VIDEO_STATE_TIME_ON, 0);
860   DrawVideoDisplay(VIDEO_STATE_FRAME_ON, 0);
861
862   MapTapeWarpButton();
863
864   SetDrawDeactivationMask(REDRAW_NONE);
865   audio.sound_deactivated = FALSE;
866 }
867
868 static void TapeStartGamePlaying(void)
869 {
870   TapeStartPlaying();
871
872   InitGame();
873 }
874
875 void TapeStopPlaying(void)
876 {
877   tape.playing = FALSE;
878   tape.pausing = FALSE;
879
880   if (tape.warp_forward)
881     TapeStopWarpForward();
882
883   DrawVideoDisplay(VIDEO_STATE_PLAY_OFF, 0);
884   MapTapeEjectButton();
885 }
886
887 byte *TapePlayAction(void)
888 {
889   int update_delay = FRAMES_PER_SECOND / 2;
890   boolean update_video_display = (FrameCounter % update_delay == 0);
891   boolean update_draw_label_on = ((FrameCounter / update_delay) % 2 == 1);
892   static byte action[MAX_TAPE_ACTIONS];
893   int i;
894
895   if (!tape.playing || tape.pausing)
896     return NULL;
897
898   if (tape.pause_before_end)  // stop some seconds before end of tape
899   {
900     if (TapeTime > tape.length_seconds - TAPE_PAUSE_SECONDS_BEFORE_DEATH)
901     {
902       TapeStopWarpForward();
903       TapeTogglePause(TAPE_TOGGLE_MANUAL);
904
905       return NULL;
906     }
907   }
908
909   if (tape.counter >= tape.length)      // end of tape reached
910   {
911     if (tape.warp_forward && !tape.auto_play)
912     {
913       TapeStopWarpForward();
914       TapeTogglePause(TAPE_TOGGLE_MANUAL);
915     }
916     else
917     {
918       TapeStop();
919     }
920
921     return NULL;
922   }
923
924   if (update_video_display && !tape.deactivate_display)
925   {
926     int state = 0;
927
928     if (tape.warp_forward)
929       state |= VIDEO_STATE_WARP(update_draw_label_on);
930     else if (tape.fast_forward)
931       state |= VIDEO_STATE_FFWD(update_draw_label_on);
932
933     if (tape.pause_before_end)
934       state |= VIDEO_STATE_PBEND(update_draw_label_on);
935
936     // draw labels and symbols separately to prevent labels overlapping symbols
937     DrawVideoDisplayLabel(state);
938     DrawVideoDisplaySymbol(state);
939   }
940
941   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
942     action[i] = tape.pos[tape.counter].action[i];
943
944 #if DEBUG_TAPE_WHEN_PLAYING
945   DebugContinued("", "%05d", FrameCounter);
946   for (i = 0; i < MAX_TAPE_ACTIONS; i++)
947     DebugContinued("", "   %08x", action[i]);
948   DebugContinued("tape:play", "\n");
949 #endif
950
951   tape.set_centered_player = FALSE;
952   tape.centered_player_nr_next = -999;
953
954   if (tape.use_key_actions)
955   {
956     for (i = 0; i < MAX_PLAYERS; i++)
957     {
958       if (action[i] & KEY_SET_FOCUS)
959       {
960         tape.set_centered_player = TRUE;
961         tape.centered_player_nr_next =
962           (tape.centered_player_nr_next == -999 ? i : -1);
963       }
964
965       action[i] &= ~KEY_SET_FOCUS;
966     }
967   }
968
969   tape.delay_played++;
970   if (tape.delay_played >= tape.pos[tape.counter].delay)
971   {
972     tape.counter++;
973     tape.delay_played = 0;
974   }
975
976   if (tape.auto_play)
977     PrintTapeReplayProgress(FALSE);
978
979   if (options.tape_log_filename != NULL)
980     WriteTapeLogfile(action);
981
982   return action;
983 }
984
985 void TapeStop(void)
986 {
987   if (tape.pausing)
988     TapeTogglePause(TAPE_TOGGLE_MANUAL);
989
990   TapeStopRecording();
991   TapeStopPlaying();
992
993   DrawVideoDisplay(VIDEO_STATE_OFF, 0);
994
995   if (tape.date && tape.length)
996   {
997     DrawVideoDisplay(VIDEO_STATE_DATE_ON, tape.date);
998     DrawVideoDisplay(VIDEO_STATE_TIME_ON, tape.length_seconds);
999     DrawVideoDisplay(VIDEO_STATE_FRAME_ON, tape.length_frames);
1000   }
1001 }
1002
1003 unsigned int GetTapeLengthFrames(void)
1004 {
1005   unsigned int tape_length_frames = 0;
1006   int i;
1007
1008   if (TAPE_IS_EMPTY(tape))
1009     return 0;
1010
1011   for (i = 0; i < tape.length; i++)
1012     tape_length_frames += tape.pos[i].delay;
1013
1014   return tape_length_frames;
1015 }
1016
1017 unsigned int GetTapeLengthSeconds(void)
1018 {
1019   return (GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
1020 }
1021
1022 static float GetTapeLengthSecondsFloat(void)
1023 {
1024   return ((float)GetTapeLengthFrames() * GAME_FRAME_DELAY / 1000);
1025 }
1026
1027 static void TapeStartWarpForward(int mode)
1028 {
1029   tape.fast_forward = (mode & AUTOPLAY_FFWD);
1030   tape.warp_forward = (mode & AUTOPLAY_WARP);
1031   tape.deactivate_display = (mode & AUTOPLAY_WARP_NO_DISPLAY);
1032
1033   tape.pausing = FALSE;
1034
1035   if (tape.deactivate_display)
1036     TapeDeactivateDisplayOn();
1037
1038   DrawVideoDisplayCurrentState();
1039 }
1040
1041 static void TapeStopWarpForward(void)
1042 {
1043   tape.fast_forward = FALSE;
1044   tape.warp_forward = FALSE;
1045   tape.deactivate_display = FALSE;
1046
1047   tape.pause_before_end = FALSE;
1048
1049   TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
1050
1051   DrawVideoDisplayCurrentState();
1052 }
1053
1054 static void TapeSingleStep(void)
1055 {
1056   if (network.enabled)
1057     return;
1058
1059   if (!tape.pausing)
1060     TapeTogglePause(TAPE_TOGGLE_MANUAL);
1061
1062   tape.single_step = !tape.single_step;
1063
1064   DrawVideoDisplay(VIDEO_STATE_1STEP(tape.single_step), 0);
1065 }
1066
1067 void TapeQuickSave(void)
1068 {
1069   if (game_status == GAME_MODE_MAIN)
1070   {
1071     Request("No game that can be saved!", REQ_CONFIRM);
1072
1073     return;
1074   }
1075
1076   if (game_status != GAME_MODE_PLAYING)
1077     return;
1078
1079   if (tape.recording)
1080     TapeHaltRecording();        // prepare tape for saving on-the-fly
1081
1082   if (TAPE_IS_EMPTY(tape))
1083   {
1084     Request("No tape that can be saved!", REQ_CONFIRM);
1085
1086     return;
1087   }
1088
1089   tape.property_bits |= TAPE_PROPERTY_SNAPSHOT;
1090
1091   if (SaveTapeChecked(tape.level_nr))
1092     SaveEngineSnapshotSingle();
1093 }
1094
1095 void TapeQuickLoad(void)
1096 {
1097   char *filename = getTapeFilename(level_nr);
1098
1099   if (!fileExists(filename))
1100   {
1101     Request("No tape for this level!", REQ_CONFIRM);
1102
1103     return;
1104   }
1105
1106   if (tape.recording && !Request("Stop recording and load tape?",
1107                                  REQ_ASK | REQ_STAY_CLOSED))
1108   {
1109     OpenDoor(DOOR_OPEN_1 | DOOR_COPY_BACK);
1110
1111     return;
1112   }
1113
1114   if (game_status != GAME_MODE_PLAYING && game_status != GAME_MODE_MAIN)
1115     return;
1116
1117   if (CheckEngineSnapshotSingle())
1118   {
1119     TapeStartGamePlaying();
1120
1121     LoadEngineSnapshotSingle();
1122
1123     DrawCompleteVideoDisplay();
1124
1125     tape.playing = TRUE;
1126     tape.pausing = TRUE;
1127
1128     TapeStopWarpForward();
1129     TapeAppendRecording();
1130
1131     // restart step/move snapshots after quick loading tape
1132     SaveEngineSnapshotToListInitial();
1133
1134     if (FrameCounter > 0)
1135       return;
1136   }
1137
1138   TapeStop();
1139   TapeErase();
1140
1141   LoadTape(level_nr);
1142
1143   if (!TAPE_IS_EMPTY(tape))
1144   {
1145     TapeStartGamePlaying();
1146     TapeStartWarpForward(AUTOPLAY_MODE_WARP_NO_DISPLAY);
1147
1148     tape.quick_resume = TRUE;
1149     tape.property_bits |= TAPE_PROPERTY_SNAPSHOT;
1150   }
1151   else  // this should not happen (basically checked above)
1152   {
1153     int reopen_door = (game_status == GAME_MODE_PLAYING ? REQ_REOPEN : 0);
1154
1155     Request("No tape for this level!", REQ_CONFIRM | reopen_door);
1156   }
1157 }
1158
1159 boolean hasSolutionTape(void)
1160 {
1161   boolean tape_file_exists = fileExists(getSolutionTapeFilename(level_nr));
1162   boolean level_has_tape = (level.game_engine_type == GAME_ENGINE_TYPE_SP &&
1163                             level.native_sp_level->demo.is_available);
1164
1165   return (tape_file_exists || level_has_tape);
1166 }
1167
1168 boolean InsertSolutionTape(void)
1169 {
1170   if (!hasSolutionTape())
1171   {
1172     Request("No solution tape for this level!", REQ_CONFIRM);
1173
1174     return FALSE;
1175   }
1176
1177   if (!TAPE_IS_STOPPED(tape))
1178     TapeStop();
1179
1180   // if tape recorder already contains a tape, remove it without asking
1181   TapeErase();
1182
1183   LoadSolutionTape(level_nr);
1184
1185   DrawCompleteVideoDisplay();
1186
1187   if (TAPE_IS_EMPTY(tape))
1188   {
1189     Request("Loading solution tape for this level failed!", REQ_CONFIRM);
1190
1191     return FALSE;
1192   }
1193
1194   return TRUE;
1195 }
1196
1197 boolean PlaySolutionTape(void)
1198 {
1199   if (!InsertSolutionTape())
1200     return FALSE;
1201
1202   TapeStartGamePlaying();
1203
1204   return TRUE;
1205 }
1206
1207 static boolean checkTapesFromSameLevel(struct TapeInfo *t1, struct TapeInfo *t2)
1208 {
1209   return (strEqual(t1->level_identifier, t2->level_identifier) &&
1210           t1->level_nr == t2->level_nr);
1211 }
1212
1213 static void CopyTape(struct TapeInfo *tape_from, struct TapeInfo *tape_to)
1214 {
1215   *tape_to = *tape_from;
1216 }
1217
1218 static void SwapTapes(struct TapeInfo *t1, struct TapeInfo *t2)
1219 {
1220   struct TapeInfo tmp = *t1;
1221
1222   *t1 = *t2;
1223   *t2 = tmp;
1224 }
1225
1226 static void CopyTapeToUndoBuffer(void)
1227 {
1228   // copy tapes to undo buffer if large enough (or larger than last undo tape)
1229   // or if the last undo tape is from a different level set or level number
1230   if (tape.length_seconds >= TAPE_MIN_SECONDS_FOR_UNDO_BUFFER ||
1231       tape.length_seconds >= tape_undo_buffer.length_seconds ||
1232       !checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1233   {
1234     CopyTape(&tape, &tape_undo_buffer);
1235   }
1236 }
1237
1238 void UndoTape(void)
1239 {
1240   // only undo tapes from same level set and with same level number
1241   if (!checkTapesFromSameLevel(&tape, &tape_undo_buffer))
1242     return;
1243
1244   if (!TAPE_IS_STOPPED(tape))
1245     TapeStop();
1246
1247   // swap last recorded tape with undo buffer, so undo can be reversed
1248   SwapTapes(&tape, &tape_undo_buffer);
1249
1250   DrawCompleteVideoDisplay();
1251 }
1252
1253 void FixTape_ForceSinglePlayer(void)
1254 {
1255   int i;
1256
1257   /* fix single-player tapes that contain player input for more than one
1258      player (due to a bug in 3.3.1.2 and earlier versions), which results
1259      in playing levels with more than one player in multi-player mode,
1260      even though the tape was originally recorded in single-player mode */
1261
1262   // remove player input actions for all players but the first one
1263   for (i = 1; i < MAX_PLAYERS; i++)
1264     tape.player_participates[i] = FALSE;
1265
1266   tape.changed = TRUE;
1267 }
1268
1269
1270 // ----------------------------------------------------------------------------
1271 // tape autoplay functions
1272 // ----------------------------------------------------------------------------
1273
1274 static void AutoPlayTapes_SetScoreEntry(int score, int time)
1275 {
1276   // set unique basename for score tape (for uploading to score server)
1277   strcpy(tape.score_tape_basename, getScoreTapeBasename(setup.player_name));
1278
1279   // store score in first score entry
1280   scores.last_added = 0;
1281
1282   struct ScoreEntry *entry = &scores.entry[scores.last_added];
1283
1284   strncpy(entry->tape_basename, tape.score_tape_basename, MAX_FILENAME_LEN);
1285   strncpy(entry->name, setup.player_name, MAX_PLAYER_NAME_LEN);
1286
1287   entry->score = score;
1288   entry->time = time;
1289
1290   PrintNoLog("- uploading score tape to score server ... ");
1291
1292   server_scores.uploaded = FALSE;
1293 }
1294
1295 static void AutoPlayTapes_WaitForUpload(void)
1296 {
1297   unsigned int upload_delay = 0;
1298   unsigned int upload_delay_value = 10000;
1299
1300   ResetDelayCounter(&upload_delay);
1301
1302   // wait for score tape to be successfully uploaded (and fail on timeout)
1303   while (!server_scores.uploaded)
1304   {
1305     if (DelayReached(&upload_delay, upload_delay_value))
1306     {
1307       PrintNoLog("\r");
1308       Print("- uploading score tape to score server - TIMEOUT.\n");
1309
1310       Fail("cannot upload score tape to score server");
1311     }
1312
1313     Delay(20);
1314   }
1315
1316   PrintNoLog("\r");
1317   Print("- uploading score tape to score server - uploaded.\n");
1318 }
1319
1320 void AutoPlayTapes(void)
1321 {
1322   static LevelDirTree *autoplay_leveldir = NULL;
1323   static boolean autoplay_initialized = FALSE;
1324   static int autoplay_last_level_nr = -1;
1325   static int autoplay_level_nr = -1;
1326   static int num_levels_played = 0;
1327   static int num_levels_solved = 0;
1328   static int num_tapes_patched = 0;
1329   static int num_tape_missing = 0;
1330   static boolean level_failed[MAX_TAPES_PER_SET];
1331   static char *tape_filename = NULL;
1332   static int patch_nr = 0;
1333   static char *patch_name[] =
1334   {
1335     "original tape",
1336     "em_random_bug",
1337     "screen_34x34",
1338
1339     NULL
1340   };
1341   static int patch_version_first[] =
1342   {
1343     VERSION_IDENT(0,0,0,0),
1344     VERSION_IDENT(3,3,1,0),
1345     VERSION_IDENT(0,0,0,0),
1346
1347     -1
1348   };
1349   static int patch_version_last[] =
1350   {
1351     VERSION_IDENT(9,9,9,9),
1352     VERSION_IDENT(4,0,1,1),
1353     VERSION_IDENT(4,2,2,0),
1354
1355     -1
1356   };
1357   static byte patch_property_bit[] =
1358   {
1359     TAPE_PROPERTY_NONE,
1360     TAPE_PROPERTY_EM_RANDOM_BUG,
1361     TAPE_PROPERTY_NONE,
1362
1363     -1
1364   };
1365   int i;
1366
1367   if (autoplay_initialized)
1368   {
1369     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1370     {
1371       if (tape.auto_play_level_solved)
1372       {
1373         if (patch_nr > 0)
1374         {
1375           // level solved by patched tape -- save fixed tape
1376           char *filename = getTapeFilename(level_nr);
1377           char *filename_orig = getStringCat2(filename, ".orig");
1378
1379           // create backup from old tape, if not yet existing
1380           if (!fileExists(filename_orig))
1381             rename(filename, filename_orig);
1382
1383           SaveTapeToFilename(filename);
1384
1385           tape.auto_play_level_fixed = TRUE;
1386           num_tapes_patched++;
1387         }
1388
1389         // continue with next tape
1390         patch_nr = 0;
1391       }
1392       else if (patch_name[patch_nr + 1] != NULL)
1393       {
1394         // level not solved by patched tape -- continue with next patch
1395         patch_nr++;
1396       }
1397       else
1398       {
1399         // level not solved by any patched tape -- continue with next tape
1400         tape.auto_play_level_not_fixable = TRUE;
1401         patch_nr = 0;
1402       }
1403     }
1404
1405     // just finished auto-playing tape
1406     PrintTapeReplayProgress(TRUE);
1407
1408     if (options.tape_log_filename != NULL)
1409       CloseTapeLogfile();
1410
1411     if (global.autoplay_mode == AUTOPLAY_MODE_SAVE &&
1412         tape.auto_play_level_solved)
1413     {
1414       AutoPlayTapes_SetScoreEntry(game.score_final, game.score_time_final);
1415
1416       if (leveldir_current)
1417       {
1418         // the tape's level set identifier may differ from current level set
1419         strncpy(tape.level_identifier, leveldir_current->identifier,
1420                 MAX_FILENAME_LEN);
1421         tape.level_identifier[MAX_FILENAME_LEN] = '\0';
1422
1423         // the tape's level number may differ from current level number
1424         tape.level_nr = level_nr;
1425       }
1426
1427       // save score tape to upload to server; may be required for some reasons:
1428       // * level set identifier in solution tapes may differ from level set
1429       // * solution tape may have native format (like Supaplex solution files)
1430
1431       SaveScoreTape(level_nr);
1432       SaveServerScore(level_nr);
1433
1434       AutoPlayTapes_WaitForUpload();
1435     }
1436
1437     if (patch_nr == 0)
1438       num_levels_played++;
1439
1440     if (tape.auto_play_level_solved)
1441       num_levels_solved++;
1442
1443     if (level_nr >= 0 && level_nr < MAX_TAPES_PER_SET)
1444       level_failed[level_nr] = !tape.auto_play_level_solved;
1445   }
1446   else
1447   {
1448     if ((global.autoplay_mode == AUTOPLAY_MODE_SAVE ||
1449          global.autoplay_mode == AUTOPLAY_MODE_UPLOAD) &&
1450         !options.mytapes &&
1451         options.player_name == NULL)
1452     {
1453       Fail("specify player name when uploading solution tapes");
1454     }
1455
1456     DrawCompleteVideoDisplay();
1457
1458     audio.sound_enabled = FALSE;
1459     setup.engine_snapshot_mode = getStringCopy(STR_SNAPSHOT_MODE_OFF);
1460
1461     if (strSuffix(global.autoplay_leveldir, ".tape"))
1462     {
1463       tape_filename = global.autoplay_leveldir;
1464
1465       LoadTapeFromFilename(tape_filename);
1466
1467       if (tape.no_valid_file)
1468       {
1469         if (!fileExists(tape_filename))
1470           Fail("tape file '%s' does not exist", tape_filename);
1471         else
1472           Fail("cannot load tape file '%s'", tape_filename);
1473       }
1474
1475       global.autoplay_leveldir = tape.level_identifier;
1476
1477       if (tape.level_nr >= 0 && tape.level_nr < MAX_TAPES_PER_SET)
1478         global.autoplay_level[tape.level_nr] = TRUE;
1479
1480       global.autoplay_all = FALSE;
1481     }
1482
1483     autoplay_leveldir = getTreeInfoFromIdentifier(leveldir_first,
1484                                                   global.autoplay_leveldir);
1485
1486     if (autoplay_leveldir == NULL)
1487       Fail("no such level identifier: '%s'", global.autoplay_leveldir);
1488
1489     leveldir_current = autoplay_leveldir;
1490
1491     if (autoplay_leveldir->first_level < 0)
1492       autoplay_leveldir->first_level = 0;
1493     if (autoplay_leveldir->last_level >= MAX_TAPES_PER_SET)
1494       autoplay_leveldir->last_level = MAX_TAPES_PER_SET - 1;
1495
1496     autoplay_level_nr = autoplay_leveldir->first_level;
1497
1498     PrintLine("=", 79);
1499     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1500       Print("Automatically fixing level tapes\n");
1501     else if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1502       Print("Automatically uploading level tapes\n");
1503     else
1504       Print("Automatically playing level tapes\n");
1505     PrintLine("-", 79);
1506     Print("Level series identifier: '%s'\n", autoplay_leveldir->identifier);
1507     Print("Level series name:       '%s'\n", autoplay_leveldir->name);
1508     Print("Level series author:     '%s'\n", autoplay_leveldir->author);
1509     Print("Number of levels:        %d\n",   autoplay_leveldir->levels);
1510     PrintLine("=", 79);
1511     Print("\n");
1512
1513     for (i = 0; i < MAX_TAPES_PER_SET; i++)
1514       level_failed[i] = FALSE;
1515
1516     // only private tapes may be modified
1517     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1518       options.mytapes = TRUE;
1519
1520     autoplay_initialized = TRUE;
1521   }
1522
1523   while (1)
1524   {
1525     if (global.autoplay_mode != AUTOPLAY_MODE_FIX || patch_nr == 0)
1526       level_nr = autoplay_level_nr++;
1527
1528     if (level_nr > autoplay_leveldir->last_level)
1529       break;
1530
1531     // set patch info (required for progress output)
1532     strcpy(tape_patch_info, "");
1533     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1534       snprintf(tape_patch_info, MAX_OUTPUT_LINESIZE, "[%-13s] ",
1535                patch_name[patch_nr]);
1536
1537     if (!global.autoplay_all && !global.autoplay_level[level_nr])
1538       continue;
1539
1540     TapeErase();
1541
1542     LoadLevel(level_nr);
1543
1544     if (level.no_level_file || level.no_valid_file)
1545     {
1546       Print("Tape %03d: (no level found)\n", level_nr);
1547
1548       continue;
1549     }
1550
1551 #if 0
1552     // ACTIVATE THIS FOR LOADING/TESTING OF LEVELS ONLY
1553     Print("Tape %03d: (only testing level)\n", level_nr);
1554     continue;
1555 #endif
1556
1557     if (tape_filename)
1558       LoadTapeFromFilename(tape_filename);
1559     else if (options.mytapes)
1560       LoadTape(level_nr);
1561     else
1562       LoadSolutionTape(level_nr);
1563
1564     if (tape.no_valid_file)
1565     {
1566       num_tape_missing++;
1567
1568       Print("Tape %03d: (no tape found)\n", level_nr);
1569
1570       continue;
1571     }
1572
1573     if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1574     {
1575       boolean skip_patch = FALSE;
1576
1577       if (tape.engine_version < patch_version_first[patch_nr] ||
1578           tape.engine_version > patch_version_last[patch_nr])
1579       {
1580         Print("Tape %03d %s[%02d:%02d]: (%s %d.%d.%d.%d) - skipped.\n",
1581               level_nr,  tape_patch_info,
1582               tape.length_seconds / 60, tape.length_seconds % 60,
1583               "not suitable for version",
1584               (tape.engine_version / 1000000) % 100,
1585               (tape.engine_version / 10000  ) % 100,
1586               (tape.engine_version / 100    ) % 100,
1587               (tape.engine_version          ) % 100);
1588
1589         skip_patch = TRUE;
1590       }
1591
1592       if (strEqual(patch_name[patch_nr], "screen_34x34") &&
1593           tape.num_participating_players == 1)
1594       {
1595         Print("Tape %03d %s[%02d:%02d]: (%s) - skipped.\n",
1596               level_nr,  tape_patch_info,
1597               tape.length_seconds / 60, tape.length_seconds % 60,
1598               "not suitable for single player tapes");
1599
1600         skip_patch = TRUE;
1601       }
1602
1603       if (skip_patch)
1604       {
1605         if (patch_name[patch_nr + 1] != NULL)
1606         {
1607           // continue with next patch
1608           patch_nr++;
1609         }
1610         else
1611         {
1612           // continue with next tape
1613           patch_nr = 0;
1614         }
1615
1616         continue;
1617       }
1618
1619       if (strEqual(patch_name[patch_nr], "screen_34x34"))
1620       {
1621         tape.scr_fieldx = SCR_FIELDX_DEFAULT * 2;
1622         tape.scr_fieldy = SCR_FIELDY_DEFAULT * 2;
1623       }
1624       else
1625       {
1626         tape.property_bits |= patch_property_bit[patch_nr];
1627       }
1628     }
1629
1630     if (global.autoplay_mode == AUTOPLAY_MODE_UPLOAD)
1631     {
1632       boolean use_temporary_tape_file = FALSE;
1633
1634       Print("Tape %03d:\n", level_nr);
1635
1636       AutoPlayTapes_SetScoreEntry(0, 0);
1637
1638       if (tape_filename == NULL)
1639       {
1640         tape_filename = (options.mytapes ? getTapeFilename(level_nr) :
1641                          getDefaultSolutionTapeFilename(level_nr));
1642
1643         if (!fileExists(tape_filename))
1644         {
1645           // non-standard solution tape -- save to temporary file
1646           tape_filename = getTemporaryTapeFilename();
1647
1648           SaveTapeToFilename(tape_filename);
1649
1650           use_temporary_tape_file = TRUE;
1651         }
1652       }
1653
1654       SaveServerScoreFromFile(level_nr, tape_filename);
1655
1656       AutoPlayTapes_WaitForUpload();
1657
1658       if (use_temporary_tape_file)
1659         unlink(tape_filename);
1660
1661       // required for uploading multiple tapes
1662       tape_filename = NULL;
1663
1664       continue;
1665     }
1666
1667     InitCounter();
1668
1669     if (options.tape_log_filename != NULL)
1670       OpenTapeLogfile();
1671
1672     TapeStartGamePlaying();
1673     TapeStartWarpForward(global.autoplay_mode);
1674
1675     autoplay_last_level_nr = level_nr;
1676
1677     return;
1678   }
1679
1680   char *autoplay_status = (num_levels_played == num_levels_solved &&
1681                            num_levels_played > 0 ? " OK " : "WARN");
1682   int autoplay_percent = (num_levels_played ?
1683                           num_levels_solved * 100 / num_levels_played : 0);
1684
1685   Print("\n");
1686   PrintLine("=", 79);
1687   Print("Number of levels played: %d\n", num_levels_played);
1688   Print("Number of levels solved: %d (%d%%)\n", num_levels_solved,
1689         (num_levels_played ? num_levels_solved * 100 / num_levels_played : 0));
1690   if (global.autoplay_mode == AUTOPLAY_MODE_FIX)
1691     Print("Number of tapes fixed: %d\n", num_tapes_patched);
1692   PrintLine("-", 79);
1693   Print("Summary (for automatic parsing by scripts):\n");
1694
1695   if (tape_filename)
1696   {
1697     Print("TAPEFILE [%s] '%s', %d, %d, %d",
1698           autoplay_status,
1699           autoplay_leveldir->identifier,
1700           autoplay_last_level_nr,
1701           game.score_final,
1702           game.score_time_final);
1703   }
1704   else
1705   {
1706     Print("LEVELDIR [%s] '%s', SOLVED %d/%d (%d%%)",
1707           autoplay_status,
1708           autoplay_leveldir->identifier,
1709           num_levels_solved,
1710           num_levels_played,
1711           autoplay_percent);
1712
1713     if (num_levels_played != num_levels_solved)
1714     {
1715       Print(", FAILED:");
1716       for (i = 0; i < MAX_TAPES_PER_SET; i++)
1717         if (level_failed[i])
1718           Print(" %03d", i);
1719     }
1720   }
1721
1722   Print("\n");
1723   PrintLine("=", 79);
1724
1725   CloseAllAndExit(0);
1726 }
1727
1728
1729 // ----------------------------------------------------------------------------
1730 // tape patch functions
1731 // ----------------------------------------------------------------------------
1732
1733 static boolean PatchTape(struct TapeInfo *tape, char *mode)
1734 {
1735   Print("[%d.%d.%d.%d]: ",
1736         (tape->engine_version / 1000000) % 100,
1737         (tape->engine_version / 10000  ) % 100,
1738         (tape->engine_version / 100    ) % 100,
1739         (tape->engine_version          ) % 100);
1740
1741   if (strEqual(mode, "info"))
1742   {
1743     Print("property bits == 0x%02x\n", tape->property_bits);
1744
1745     return FALSE;
1746   }
1747
1748   boolean unpatch_tape = FALSE;
1749   boolean use_property_bit = FALSE;
1750   byte property_bitmask = 0;
1751
1752   if (strSuffix(mode, ":0") ||
1753       strSuffix(mode, ":off") ||
1754       strSuffix(mode, ":clear"))
1755     unpatch_tape = TRUE;
1756
1757   if (strEqual(mode, "em_random_bug") || strPrefix(mode, "em_random_bug:"))
1758   {
1759     // this bug was introduced in version 3.3.1.0 and fixed in version 4.0.1.2
1760     if (tape->engine_version <  VERSION_IDENT(3,3,1,0) ||
1761         tape->engine_version >= VERSION_IDENT(4,0,1,2))
1762     {
1763       Print("This tape version cannot be patched against EM random bug!\n");
1764
1765       return FALSE;
1766     }
1767
1768     property_bitmask = TAPE_PROPERTY_EM_RANDOM_BUG;
1769
1770     use_property_bit = TRUE;
1771   }
1772   else if (strEqual(mode, "screen_34x34") || strPrefix(mode, "screen_34x34:"))
1773   {
1774     // this bug only affects team mode tapes
1775     if (tape->num_participating_players == 1)
1776     {
1777       Print("Only team mode tapes can be patched against screen size bug!\n");
1778
1779       return FALSE;
1780     }
1781
1782     // this bug (that always existed before) was fixed in version 4.2.2.1
1783     if (tape->engine_version >= VERSION_IDENT(4,2,2,1))
1784     {
1785       Print("This tape version cannot be patched against screen size bug!\n");
1786
1787       return FALSE;
1788     }
1789
1790     int factor = (unpatch_tape ? 1 : 2);
1791     int scr_fieldx_new = SCR_FIELDX_DEFAULT * factor;
1792     int scr_fieldy_new = SCR_FIELDY_DEFAULT * factor;
1793
1794     if (scr_fieldx_new == tape->scr_fieldx &&
1795         scr_fieldy_new == tape->scr_fieldy)
1796     {
1797       Print("Tape already patched for '%s'!\n", mode);
1798
1799       return FALSE;
1800     }
1801
1802     tape->scr_fieldx = scr_fieldx_new;
1803     tape->scr_fieldy = scr_fieldy_new;
1804   }
1805   else
1806   {
1807     Print("Unknown patch mode '%s'!\n", mode);
1808
1809     return FALSE;
1810   }
1811
1812   // patching tapes using property bits may be used for several patch modes
1813   if (use_property_bit)
1814   {
1815     byte property_bits = tape->property_bits;
1816     boolean set_property_bit = (unpatch_tape ? FALSE : TRUE);
1817
1818     if (set_property_bit)
1819       property_bits |= property_bitmask;
1820     else
1821       property_bits &= ~property_bitmask;
1822
1823     if (property_bits == tape->property_bits)
1824     {
1825       Print("Tape already patched for '%s'!\n", mode);
1826
1827       return FALSE;
1828     }
1829
1830     tape->property_bits = property_bits;
1831   }
1832
1833   Print("Patching for '%s' ... ", mode);
1834
1835   return TRUE;
1836 }
1837
1838 void PatchTapes(void)
1839 {
1840   static LevelDirTree *patchtapes_leveldir = NULL;
1841   static int num_tapes_found = 0;
1842   static int num_tapes_patched = 0;
1843   char *mode = global.patchtapes_mode;
1844   int i;
1845
1846   if (strEqual(mode, "help"))
1847   {
1848     PrintLine("=", 79);
1849     Print("Supported patch modes:\n");
1850     Print("- \"em_random_bug\"   - use 64-bit random value bug for EM engine\n");
1851     Print("- \"screen_34x34\"    - force visible playfield size of 34 x 34\n");
1852     PrintLine("-", 79);
1853     Print("Supported modifiers:\n");
1854     Print("- add \":0\", \":off\" or \":clear\" to patch mode to un-patch tape file\n");
1855     PrintLine("=", 79);
1856
1857     CloseAllAndExit(0);
1858   }
1859
1860   patchtapes_leveldir = getTreeInfoFromIdentifier(leveldir_first,
1861                                                   global.patchtapes_leveldir);
1862
1863   if (patchtapes_leveldir == NULL)
1864     Fail("no such level identifier: '%s'", global.patchtapes_leveldir);
1865
1866   leveldir_current = patchtapes_leveldir;
1867
1868   if (patchtapes_leveldir->first_level < 0)
1869     patchtapes_leveldir->first_level = 0;
1870   if (patchtapes_leveldir->last_level >= MAX_TAPES_PER_SET)
1871     patchtapes_leveldir->last_level = MAX_TAPES_PER_SET - 1;
1872
1873   PrintLine("=", 79);
1874   Print("Patching level tapes for patch mode '%s'\n", mode);
1875   PrintLine("-", 79);
1876   Print("Level series identifier: '%s'\n", patchtapes_leveldir->identifier);
1877   Print("Level series name:       '%s'\n", patchtapes_leveldir->name);
1878   Print("Level series author:     '%s'\n", patchtapes_leveldir->author);
1879   Print("Number of levels:        %d\n",   patchtapes_leveldir->levels);
1880   PrintLine("=", 79);
1881   Print("\n");
1882
1883   int first_level = patchtapes_leveldir->first_level;
1884   int last_level = patchtapes_leveldir->last_level;
1885
1886   for (i = first_level; i <= last_level; i++)
1887   {
1888     if (!global.patchtapes_all && !global.patchtapes_level[i])
1889       continue;
1890
1891     Print("Tape %03d: ", i);
1892
1893     TapeErase();
1894     LoadTape(i);
1895
1896     if (tape.no_valid_file)
1897     {
1898       Print("(no tape found)\n");
1899
1900       continue;
1901     }
1902
1903     num_tapes_found++;
1904
1905     if (PatchTape(&tape, mode))
1906     {
1907       char *filename = getTapeFilename(i);
1908       char *filename_orig = getStringCat2(filename, ".orig");
1909
1910       if (!fileExists(filename_orig))
1911         rename(filename, filename_orig);
1912
1913       SaveTapeToFilename(filename);
1914
1915       Print("patched tape saved.\n");
1916
1917       num_tapes_patched++;
1918     }
1919   }
1920
1921   Print("\n");
1922   PrintLine("=", 79);
1923   Print("Number of tapes found: %d\n", num_tapes_found);
1924   Print("Number of tapes patched: %d\n", num_tapes_patched);
1925   PrintLine("=", 79);
1926
1927   CloseAllAndExit(0);
1928 }
1929
1930
1931 // ---------- new tape button stuff -------------------------------------------
1932
1933 static struct
1934 {
1935   int graphic;
1936   struct XY *pos;
1937   int gadget_id;
1938   char *infotext;
1939 } tapebutton_info[NUM_TAPE_BUTTONS] =
1940 {
1941   {
1942     IMG_GFX_TAPE_BUTTON_EJECT,          &tape.button.eject,
1943     TAPE_CTRL_ID_EJECT,                 "eject tape"
1944   },
1945   {
1946     // (same position as "eject" button)
1947     IMG_GFX_TAPE_BUTTON_EXTRA,          &tape.button.eject,
1948     TAPE_CTRL_ID_EXTRA,                 "extra functions"
1949   },
1950   {
1951     IMG_GFX_TAPE_BUTTON_STOP,           &tape.button.stop,
1952     TAPE_CTRL_ID_STOP,                  "stop tape"
1953   },
1954   {
1955     IMG_GFX_TAPE_BUTTON_PAUSE,          &tape.button.pause,
1956     TAPE_CTRL_ID_PAUSE,                 "pause tape"
1957   },
1958   {
1959     IMG_GFX_TAPE_BUTTON_RECORD,         &tape.button.record,
1960     TAPE_CTRL_ID_RECORD,                "record tape"
1961   },
1962   {
1963     IMG_GFX_TAPE_BUTTON_PLAY,           &tape.button.play,
1964     TAPE_CTRL_ID_PLAY,                  "play tape"
1965   },
1966   {
1967     IMG_GFX_TAPE_BUTTON_INSERT_SOLUTION,&tape.button.insert_solution,
1968     TAPE_CTRL_ID_INSERT_SOLUTION,       "insert solution tape"
1969   },
1970   {
1971     IMG_GFX_TAPE_BUTTON_PLAY_SOLUTION,  &tape.button.play_solution,
1972     TAPE_CTRL_ID_PLAY_SOLUTION,         "play solution tape"
1973   }
1974 };
1975
1976 void CreateTapeButtons(void)
1977 {
1978   int i;
1979
1980   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
1981   {
1982     int graphic = tapebutton_info[i].graphic;
1983     struct GraphicInfo *gfx = &graphic_info[graphic];
1984     struct XY *pos = tapebutton_info[i].pos;
1985     struct GadgetInfo *gi;
1986     int gd_x = gfx->src_x;
1987     int gd_y = gfx->src_y;
1988     int gd_xp = gfx->src_x + gfx->pressed_xoffset;
1989     int gd_yp = gfx->src_y + gfx->pressed_yoffset;
1990     int id = i;
1991
1992     gi = CreateGadget(GDI_CUSTOM_ID, id,
1993                       GDI_IMAGE_ID, graphic,
1994                       GDI_INFO_TEXT, tapebutton_info[i].infotext,
1995                       GDI_X, VX + pos->x,
1996                       GDI_Y, VY + pos->y,
1997                       GDI_WIDTH, gfx->width,
1998                       GDI_HEIGHT, gfx->height,
1999                       GDI_TYPE, GD_TYPE_NORMAL_BUTTON,
2000                       GDI_STATE, GD_BUTTON_UNPRESSED,
2001                       GDI_DESIGN_UNPRESSED, gfx->bitmap, gd_x, gd_y,
2002                       GDI_DESIGN_PRESSED, gfx->bitmap, gd_xp, gd_yp,
2003                       GDI_DIRECT_DRAW, FALSE,
2004                       GDI_EVENT_MASK, GD_EVENT_RELEASED,
2005                       GDI_CALLBACK_ACTION, HandleTapeButtons,
2006                       GDI_END);
2007
2008     if (gi == NULL)
2009       Fail("cannot create gadget");
2010
2011     tape_gadget[id] = gi;
2012   }
2013 }
2014
2015 void FreeTapeButtons(void)
2016 {
2017   int i;
2018
2019   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2020     FreeGadget(tape_gadget[i]);
2021 }
2022
2023 void MapTapeEjectButton(void)
2024 {
2025   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
2026   MapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
2027 }
2028
2029 void MapTapeWarpButton(void)
2030 {
2031   UnmapGadget(tape_gadget[TAPE_CTRL_ID_EJECT]);
2032   MapGadget(tape_gadget[TAPE_CTRL_ID_EXTRA]);
2033 }
2034
2035 void MapTapeButtons(void)
2036 {
2037   int i;
2038
2039   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2040     if (i != TAPE_CTRL_ID_EXTRA)
2041       MapGadget(tape_gadget[i]);
2042
2043   if (tape.recording || tape.playing)
2044     MapTapeWarpButton();
2045
2046   if (tape.show_game_buttons)
2047     MapGameButtonsOnTape();
2048 }
2049
2050 void UnmapTapeButtons(void)
2051 {
2052   int i;
2053
2054   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2055     UnmapGadget(tape_gadget[i]);
2056
2057   if (tape.show_game_buttons)
2058     UnmapGameButtonsOnTape();
2059 }
2060
2061 void RedrawTapeButtons(void)
2062 {
2063   int i;
2064
2065   for (i = 0; i < NUM_TAPE_BUTTONS; i++)
2066     RedrawGadget(tape_gadget[i]);
2067
2068   if (tape.show_game_buttons)
2069     RedrawGameButtonsOnTape();
2070 }
2071
2072 void RedrawOrRemapTapeButtons(void)
2073 {
2074   if (tape_gadget[TAPE_CTRL_ID_PLAY]->mapped)
2075   {
2076     // tape buttons already mapped
2077     RedrawTapeButtons();
2078   }
2079   else
2080   {
2081     UnmapTapeButtons();
2082     MapTapeButtons();
2083   }
2084 }
2085
2086 static void HandleTapeButtonsExt(int id)
2087 {
2088   if (game_status != GAME_MODE_MAIN && game_status != GAME_MODE_PLAYING)
2089     return;
2090
2091   switch (id)
2092   {
2093     case TAPE_CTRL_ID_EJECT:
2094       TapeStop();
2095
2096       if (TAPE_IS_EMPTY(tape))
2097       {
2098         LoadTape(level_nr);
2099
2100         if (TAPE_IS_EMPTY(tape))
2101           Request("No tape for this level!", REQ_CONFIRM);
2102       }
2103       else
2104       {
2105         if (tape.changed)
2106           SaveTapeChecked(level_nr);
2107
2108         TapeErase();
2109       }
2110
2111       DrawCompleteVideoDisplay();
2112       break;
2113
2114     case TAPE_CTRL_ID_EXTRA:
2115       if (tape.playing)
2116       {
2117         tape.pause_before_end = !tape.pause_before_end;
2118
2119         DrawVideoDisplayCurrentState();
2120       }
2121       else if (tape.recording)
2122       {
2123         TapeSingleStep();
2124       }
2125
2126       break;
2127
2128     case TAPE_CTRL_ID_STOP:
2129       TapeStop();
2130
2131       break;
2132
2133     case TAPE_CTRL_ID_PAUSE:
2134       TapeTogglePause(TAPE_TOGGLE_MANUAL);
2135
2136       break;
2137
2138     case TAPE_CTRL_ID_RECORD:
2139       if (TAPE_IS_STOPPED(tape))
2140       {
2141         TapeStartGameRecording();
2142       }
2143       else if (tape.pausing)
2144       {
2145         if (tape.playing)                       // PLAY -> PAUSE -> RECORD
2146           TapeAppendRecording();
2147         else
2148           TapeTogglePause(TAPE_TOGGLE_MANUAL);
2149       }
2150
2151       break;
2152
2153     case TAPE_CTRL_ID_PLAY:
2154       if (tape.recording && tape.pausing)       // PAUSE -> RECORD
2155       {
2156         // ("TAPE_IS_EMPTY(tape)" is TRUE here -- probably fix this)
2157
2158         TapeTogglePause(TAPE_TOGGLE_MANUAL);
2159       }
2160
2161       if (TAPE_IS_EMPTY(tape))
2162         break;
2163
2164       if (TAPE_IS_STOPPED(tape))
2165       {
2166         TapeStartGamePlaying();
2167       }
2168       else if (tape.playing)
2169       {
2170         if (tape.pausing)                       // PAUSE -> PLAY
2171         {
2172           TapeTogglePause(TAPE_TOGGLE_MANUAL | TAPE_TOGGLE_PLAY_PAUSE);
2173         }
2174         else if (!tape.fast_forward)            // PLAY -> FFWD
2175         {
2176           tape.fast_forward = TRUE;
2177         }
2178         else if (!tape.warp_forward)            // FFWD -> WARP
2179         {
2180           tape.warp_forward = TRUE;
2181         }
2182         else if (!tape.deactivate_display)      // WARP -> WARP BLIND
2183         {
2184           tape.deactivate_display = TRUE;
2185
2186           TapeDeactivateDisplayOn();
2187         }
2188         else                                    // WARP BLIND -> PLAY
2189         {
2190           tape.fast_forward = FALSE;
2191           tape.warp_forward = FALSE;
2192           tape.deactivate_display = FALSE;
2193
2194           TapeDeactivateDisplayOff(game_status == GAME_MODE_PLAYING);
2195         }
2196
2197         DrawVideoDisplayCurrentState();
2198       }
2199
2200       break;
2201
2202     case TAPE_CTRL_ID_INSERT_SOLUTION:
2203       InsertSolutionTape();
2204
2205       break;
2206
2207     case TAPE_CTRL_ID_PLAY_SOLUTION:
2208       PlaySolutionTape();
2209
2210       break;
2211
2212     default:
2213       break;
2214   }
2215 }
2216
2217 static void HandleTapeButtons(struct GadgetInfo *gi)
2218 {
2219   HandleTapeButtonsExt(gi->custom_id);
2220 }
2221
2222 void HandleTapeButtonKeys(Key key)
2223 {
2224   boolean eject_button_is_active = TAPE_IS_STOPPED(tape);
2225   boolean extra_button_is_active = !eject_button_is_active;
2226
2227   if (key == setup.shortcut.tape_eject && eject_button_is_active)
2228     HandleTapeButtonsExt(TAPE_CTRL_ID_EJECT);
2229   else if (key == setup.shortcut.tape_extra && extra_button_is_active)
2230     HandleTapeButtonsExt(TAPE_CTRL_ID_EXTRA);
2231   else if (key == setup.shortcut.tape_stop)
2232     HandleTapeButtonsExt(TAPE_CTRL_ID_STOP);
2233   else if (key == setup.shortcut.tape_pause)
2234     HandleTapeButtonsExt(TAPE_CTRL_ID_PAUSE);
2235   else if (key == setup.shortcut.tape_record)
2236     HandleTapeButtonsExt(TAPE_CTRL_ID_RECORD);
2237   else if (key == setup.shortcut.tape_play)
2238     HandleTapeButtonsExt(TAPE_CTRL_ID_PLAY);
2239 }