/*
 * fsdir.c — directory operations via ESTEX:
 *   $1B MKDIR   — create directory (HL = path)
 *   $1C RMDIR   — remove empty directory (HL = path)
 *   $1D CHDIR   — change current directory (HL = path)
 *   $1E CURDIR  — read current directory path (HL = 256-byte buffer)
 *
 * All four return CF=1 + A=error on failure.  We surface that as errno
 * with a -1 (or NULL for getcwd) return value, matching POSIX.
 */

#include <unistd.h>
#include <errno.h>

int mkdir(const char *path) __naked
{
    (void)path;
    __asm
        push  ix
        ld    c, #0x1B              ; ESTEX MKDIR; HL already = path
        rst   #0x10
        pop   ix
        jr    c, _mk_err
        ld    de, #0
        ret
    _mk_err:
        call  __errno_set
        ld    de, #-1
        ret
    __endasm;
}

int rmdir(const char *path) __naked
{
    (void)path;
    __asm
        push  ix
        ld    c, #0x1C              ; ESTEX RMDIR; HL already = path
        rst   #0x10
        pop   ix
        jr    c, _rm_err
        ld    de, #0
        ret
    _rm_err:
        call  __errno_set
        ld    de, #-1
        ret
    __endasm;
}

int chdir(const char *path) __naked
{
    (void)path;
    __asm
        push  ix
        ld    c, #0x1D              ; ESTEX CHDIR; HL already = path
        rst   #0x10
        pop   ix
        jr    c, _cd_err
        ld    de, #0
        ret
    _cd_err:
        call  __errno_set
        ld    de, #-1
        ret
    __endasm;
}

char *getcwd(char *buf, size_t size) __naked
{
    (void)buf; (void)size;
    __asm
        ;; HL = buf, DE = size (ignored — ESTEX always wants 256 bytes).
        push  ix
        push  hl                    ; preserve buf across RST
        ld    c, #0x1E              ; ESTEX CURDIR
        rst   #0x10
        pop   hl                    ; restore buf
        pop   ix
        jr    c, _gc_err
        ex    de, hl                ; return buf via DE (SDCC ptr return)
        ret
    _gc_err:
        call  __errno_set
        ld    de, #0                ; NULL on error
        ret
    __endasm;
}
