// SPDX-License-Identifier: GPL-3.0-or-later
// Planet Atlas creates ATLAS.DAT on drive 0 the first time you run it.
#include <coco.h>
#include <decbfile.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>

#define ATLAS_NAME "ATLAS.DAT:0"
#define CARD_SIZE 24
static const char cards[][CARD_SIZE] = {
    "MERCURY: CRATERS", "VENUS: CLOUDS", "EARTH: BLUE SEA", "MARS: RED RIDGE"
};

/* Keep any atlas already on the disk. On a fresh disk, write four cards. */
static FILE *openAtlas(void)
{
    FILE *atlas = fopen(ATLAS_NAME, "r+b");
    int complete;
    if (atlas || vcc_file_error() != DECB_ERR_NOT_FOUND)
        return atlas;
    atlas = fopen(ATLAS_NAME, "wb");
    if (!atlas)
        return NULL;
    complete = fwrite(cards, CARD_SIZE, 4, atlas) == 4;
    if (fclose(atlas) == EOF || !complete)
        return NULL;
    return fopen(ATLAS_NAME, "r+b");
}

/* Read exactly one card from the current position. Leave room for a zero
   so even a card that fills all 24 bytes can be displayed as a C string. */
static int showCard(FILE *atlas)
{
    char card[CARD_SIZE + 1];
    if (fread(card, CARD_SIZE, 1, atlas) != 1)
        return 0;
    card[CARD_SIZE] = 0;
    printf("%s\n", card);
    return 1;
}

static int takeTrip(FILE *atlas, int number)
{
    /* Card numbers begin at 1. Disk offsets begin at 0. */
    long offset = (long)(number - 1) * CARD_SIZE;
    long bookmark;
    if (fseek(atlas, offset, SEEK_SET) != 0)
        return 0;
    bookmark = ftell(atlas);        // Save the start before reading the card.
    if (bookmark < 0)
        return 0;
    printf("YOUR PICK AT BYTE %ld\n", bookmark);
    if (!showCard(atlas))
        return 0;

    printf("HOME BASE\n");
    if (fseek(atlas, 2L * CARD_SIZE, SEEK_SET) != 0 || !showCard(atlas))
        return 0;
    printf("BACK TO YOUR BOOKMARK\n");
    if (fseek(atlas, bookmark, SEEK_SET) != 0 || !showCard(atlas))
        return 0;

    rewind(atlas);                 // The first card is Mercury again.
    printf("FIRST CARD\n");
    return ftell(atlas) == 0L && showCard(atlas);
}

/* Enter a whole record number. Base zero accepts 2 and 0x2 for Venus. */
static int choosePlanet(void)
{
    for (;;)
    {
        char *line, *end;
        unsigned long number;
        printf("PICK A PLANET (1-4), THEN ENTER\n");
        line = readline();
        if (!line)
            return 0;
        if (!isdigit((unsigned char)*line))
        {
            printf("START WITH A DIGIT\n");
            continue;
        }
        errno = 0;
        number = strtoul(line, &end, 0);
        if (*end)
            printf("EXTRA CHARACTER: %c\n", *end);
        else if (errno == ERANGE || number < 1UL || number > 4UL)
            printf("CHOOSE A NUMBER FROM 1 TO 4\n");
        else
            return (int)number;  // Now the value is small enough for an int.
    }
}

/* The last padding byte is a visit flag. A custom card that uses the whole
   field for its description has no spare byte; leave its text intact. */
static int recordVisit(FILE *atlas, int number)
{
    char card[CARD_SIZE];
    long start = (long)(number - 1) * CARD_SIZE;
    if (fseek(atlas, start, SEEK_SET) != 0 || fread(card, CARD_SIZE, 1, atlas) != 1)
        return 0;
    if (!memchr(card, 0, CARD_SIZE - 1) ||
        (card[CARD_SIZE - 1] != 0 && card[CARD_SIZE - 1] != 'V'))
    {
        printf("NO ROOM FOR VISIT MARK\n");
        return 1;
    }
    if (card[CARD_SIZE - 1] == 'V')
    {
        printf("ALREADY VISITED\n");
        return 1;
    }

    // Position the update stream between reading the card and writing its flag.
    if (fseek(atlas, start + CARD_SIZE - 1, SEEK_SET) != 0 ||
        fputc('V', atlas) == EOF || fflush(atlas) == EOF)
        return 0;
    printf("VISIT SAVED\n");
    return 1;
}

int main(void)
{
    FILE *atlas;
    int number, ok;
    cls(1);
    atlas = openAtlas();
    if (!atlas)
    {
        printf("CANNOT OPEN ATLAS.DAT\n");
        return 1;
    }
    printf("PLANET ATLAS\n1 MERCURY    2 VENUS\n3 EARTH      4 MARS\n");
    number = choosePlanet();
    if (!number)
    {
        fclose(atlas);
        printf("CANNOT READ KEYBOARD\n");
        return 1;
    }

    cls(1);
    printf("PLANET ATLAS\n\n");
    ok = takeTrip(atlas, number);
    if (!ok)
        printf("CANNOT READ ATLAS CARD\n");
    else if (!recordVisit(atlas, number))
    {
        printf("CANNOT SAVE VISIT\n");
        ok = 0;
    }
    if (fclose(atlas) == EOF)
        ok = 0;
    if (ok)
        printf("ATLAS CLOSED\n");
    return ok ? 0 : 1;
}
