/*
 * errno.c — strerror / perror over the SDCC-provided `errno` global.
 *
 * The message table mirrors the one in solid-c's IO.ASM (we kept the
 * English wording for grep-ability).  ESTEX returns codes 0..32 in the
 * meaningful range; anything beyond gets "Unknown error".
 *
 * Note: we deliberately do NOT define `_errno` here — SDCC's
 * z80.lib/errno.rel provides it (a single int in _DATA), and our libc
 * wrappers (read.c, open.c, etc.) just assign to `errno`.  This
 * removes the "multiple definition of _errno" link warning.
 */

#include <errno.h>
#include <stdio.h>
#include <string.h>

/*
 * Stored verbatim — pointers in the lookup table cost 2 bytes each plus
 * the message bytes themselves.  Sentinel "" entries pad out gaps so
 * indexing stays direct.
 */
static const char *const messages[] = {
    /*  0 */ "No error",
    /*  1 */ "Invalid function",
    /*  2 */ "Invalid drive number",
    /*  3 */ "File not found",
    /*  4 */ "Path not found",
    /*  5 */ "Invalid handle",
    /*  6 */ "Too many open files",
    /*  7 */ "File already exists",
    /*  8 */ "File is read-only",
    /*  9 */ "Root directory overflow",
    /* 10 */ "No free space",
    /* 11 */ "Directory not empty",
    /* 12 */ "Can't delete current directory",
    /* 13 */ "Invalid media",
    /* 14 */ "Unknown operation",
    /* 15 */ "Directory exists",
    /* 16 */ "Invalid filename",
    /* 17 */ "Invalid EXE file",
    /* 18 */ "Not supported EXE file",
    /* 19 */ "Access denied",
    /* 20 */ "Device not ready",
    /* 21 */ "Seek error",
    /* 22 */ "Sector not found",
    /* 23 */ "CRC error",
    /* 24 */ "Write protect",
    /* 25 */ "Read error",
    /* 26 */ "Write error",
    /* 27 */ "Drive failure",
    /* 28 */ "RESERVED",
    /* 29 */ "RESERVED",
    /* 30 */ "Out of memory",
    /* 31 */ "Invalid memory block",
    /* 32 */ "Unknown error",
};

const int ESTEX_MAX_ERR = sizeof(messages) / sizeof(messages[0]) - 1;

const char *strerror(int err)
{
    if (err < 0 || err > ESTEX_MAX_ERR) {
        err = EUNKERR;
    }
    return messages[err];
}

void perror(const char *prefix)
{
    if (prefix && *prefix) {
        fputs(prefix, stderr);
        fputs(": ", stderr);
    }
    fputs(strerror(errno), stderr);
    fputs("\r\n", stderr);
}
