// SPDX-License-Identifier: GPL-3.0-or-later
// Run twice on the same practice disk. Each flight adds one observation.
#include <coco.h>
#include <decbfile.h>
#include <stdio.h>
#include <string.h>

#define LOG_NAME "TRIP.LOG:0"

static int fly(FILE *log)
{
    char line[32];
    unsigned visits = 0;
    const char *planet;

    /* a+ opens even a new log at byte zero so we can read earlier flights. */
    while (fgets(line, sizeof(line), log))
    {
        if ((visits == 0 && strcmp(line, "VISIT 1: EARTH\n") == 0) ||
            (visits == 1 && strcmp(line, "VISIT 2: MARS\n") == 0))
            ++visits;
        else
        {
            printf("UNRECOGNIZED TRIP.LOG\n");
            return 0;
        }
    }
    if (ferror(log))
        return 0;
    if (visits == 2)
    {
        printf("BOTH VISITS ALREADY FILED\n");
        return 1;
    }

    /* Move the cursor to the first record. With a+, output still appends. */
    if (fseek(log, 0L, SEEK_SET) != 0)
        return 0;
    planet = visits ? "MARS" : "EARTH";
    printf("AT BYTE ZERO\nFILING %s\n", planet);
    if (fprintf(log, "VISIT %u: %s\n", visits + 1, planet) < 0)
        return 0;

    /* This short record is buffered. Keep the stream open if saving fails. */
    while (fflush(log) == EOF)
    {
        char key;
        if (ferror(log) != DECB_ERR_IO)
            return 0;
        printf("SAVE FAILED\nKEEP THE SAME DISK IN DRIVE 0\n");
        printf("IF PROTECTED, TURN PROTECT OFF\nR: RETRY   Q: QUIT\n");
        do {
            key = waitkey(0);
        } while (key != 'R' && key != 'r' && key != 'Q' && key != 'q');
        if (key == 'Q' || key == 'q')
            return 0;
        /* Retry just the flush. Printing the observation again could duplicate it. */
        clearerr(log);
        printf("RETRYING SAVE\n");
    }
    return 1;
}

int main(void)
{
    FILE *log;
    char line[32];
    int ok;
    cls(1);
    printf("RETURN TRIP\n");
    log = fopen(LOG_NAME, "a+");
    if (!log)
    {
        printf("CANNOT OPEN TRIP.LOG\n");
        return 1;
    }
    ok = fly(log);
    /* Check the result of closing the stream, even after an explicit flush. */
    if (fclose(log) == EOF)
        ok = 0;
    if (!ok)
    {
        printf("CHECK DISK AND LOG\n");
        return 1;
    }

    /* A new reader shows what the next flight will find on the disk. */
    log = fopen(LOG_NAME, "r");
    if (!log)
    {
        printf("CANNOT REOPEN TRIP.LOG\n");
        return 1;
    }
    printf("REOPENED TRIP.LOG\n");
    while (fgets(line, sizeof(line), log))
        printf("%s", line);
    ok = !ferror(log);
    if (fclose(log) == EOF)
        ok = 0;
    if (!ok)
    {
        printf("CANNOT READ TRIP.LOG\n");
        return 1;
    }
    return 0;
}
