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