// SPDX-License-Identifier: GPL-3.0-or-later
// Work on a practice disk. Each run starts a new FIELD.LOG on drive 0.
#include <coco.h>
#include <stdio.h>

#define LOG_NAME "FIELD.LOG:0"

/* Each reader starts at the beginning and sees the length saved on disk. */
static int showLog(void)
{
    char line[40];
    FILE *reader = fopen(LOG_NAME, "r");
    int ok;
    if (!reader)
        return 0;
    while (fgets(line, sizeof(line), reader))
        printf("%s", line);
    ok = !ferror(reader);
    if (fclose(reader) == EOF)
        ok = 0;
    return ok;
}

int main(void)
{
    FILE *writer;
    int ok;
    cls(1);
    printf("PLANET FIELD LOG\n");
    writer = fopen(LOG_NAME, "w");
    if (!writer)
    {
        printf("CANNOT START FIELD.LOG\n");
        return 1;
    }

    /* Publish the first observation while we still hold the writer. */
    ok = fputs("EARTH: BLUE SEA\n", writer) != EOF && fflush(writer) == 0;
    if (ok)
    {
        printf("CHECKPOINT READER SEES:\n");
        ok = showLog();
    }
    if (ok)
    {
        printf("SPACE TO LAND ON MARS\n");
        while (waitkey(0) != ' ') {}
        ok = fputs("MARS: RED RIDGE\n", writer) != EOF;
    }

    /* Closing delivers the second observation and releases the stream. */
    if (fclose(writer) == EOF)
        ok = 0;
    if (!ok)
    {
        printf("CHECK DISK AND LOG\n");
        return 1;
    }
    printf("FINAL READER SEES:\n");
    if (!showLog())
    {
        printf("CANNOT READ FIELD.LOG\n");
        return 1;
    }
    printf("SURVEY FILED\n");
    return 0;
}
