// SPDX-License-Identifier: GPL-3.0-or-later
// Give Mission Control two observations it can read back in recording order.
#include <coco.h>
#include <vcc/cassette.h>

static int recordFlight(void)
{
    int status = vcc_tape_open_write("FLIGHT");
    if (status != VCC_TAPE_OK)
        return status;

    status = vcc_tape_write_line("EARTH BLUE SEA");
    if (status == VCC_TAPE_OK)
        status = vcc_tape_write_line("MARS RED RIDGE");
    /* Closing writes the end-of-file block on a successful recording. */
    int closed = vcc_tape_close();
    return status == VCC_TAPE_OK ? closed : status;
}

static int replayFlight(void)
{
    char observation[32];
    int status = vcc_tape_open_read("FLIGHT");
    if (status != VCC_TAPE_OK)
        return status;

    while ((status = vcc_tape_read_line(observation, sizeof observation)) == VCC_TAPE_OK)
        printf("%s\n", observation);
    int closed = vcc_tape_close();
    /* A damaged last block also stops the loop. Only EOF completes the flight. */
    return status == VCC_TAPE_EOF ? closed : status;
}

int main(void)
{
    cls(1);
    printf("FLIGHT RECORDER\n");
    printf("W WRITE   R READ\n");
    char choice;
    do {
        choice = waitkey(0);
    } while (choice != 'W' && choice != 'w' && choice != 'R' && choice != 'r');

    int write = choice == 'W' || choice == 'w';
    int status = write ? recordFlight() : replayFlight();
    if (status != VCC_TAPE_OK) {
        printf("TAPE ERROR %d\n", status);
        return 1;
    }
    printf("%s\n", write ? "FLIGHT SAVED" : "END OF FLIGHT");
    return 0;
}
