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

#pragma import(__use_no_semihosting)

const char __stdin_name[] = ":tt";
const char __stdout_name[] = ":tt";
const char __stderr_name[] = ":tt";

#define NULL_FH_STDIN   0x8001
#define NULL_FH_STDOUT  0x8002
#define NULL_FH_STDERR  0x8003

static int rtt_is_terminal_name(const char *name)
{
    return (name != NULL) && (strcmp(name, ":tt") == 0);
}

FILEHANDLE _sys_open(const char *name, int openmode)
{
    if (!rtt_is_terminal_name(name)) {
        return -1;
    }

    if ((openmode & OPEN_W) == OPEN_W) {
        return NULL_FH_STDOUT;
    }

    if ((openmode & OPEN_A) == OPEN_A) {
        return NULL_FH_STDERR;
    }

    return NULL_FH_STDIN;
}

int _sys_close(FILEHANDLE fh)
{
    (void)fh;
    return 0;
}

int _sys_write(FILEHANDLE fh, const unsigned char *buf, unsigned len, int mode)
{
    (void)mode;

    if ((fh != NULL_FH_STDOUT) && (fh != NULL_FH_STDERR)) {
        return -1;
    }

    if ((buf == NULL) || (len == 0u)) {
        return 0;
    }

    (void)buf;
    (void)len;
    return 0;
}

int _sys_read(FILEHANDLE fh, unsigned char *buf, unsigned len, int mode)
{
    (void)fh;
    (void)buf;
    (void)len;
    (void)mode;
    return -1;
}

int _sys_istty(FILEHANDLE fh)
{
    return (fh == NULL_FH_STDIN) || (fh == NULL_FH_STDOUT) || (fh == NULL_FH_STDERR);
}

int _sys_seek(FILEHANDLE fh, long pos)
{
    (void)fh;
    (void)pos;
    return -1;
}

int _sys_ensure(FILEHANDLE fh)
{
    (void)fh;
    return 0;
}

long _sys_flen(FILEHANDLE fh)
{
    (void)fh;
    return 0;
}

int _sys_tmpnam(char *name, int sig, unsigned maxlen)
{
    (void)name;
    (void)sig;
    (void)maxlen;
    return 0;
}

char *_sys_command_string(char *cmd, int len)
{
    (void)cmd;
    (void)len;
    return NULL;
}

void _ttywrch(int ch)
{
    (void)ch;
}

void _sys_exit(int returncode)
{
    (void)returncode;
    while (1) {
    }
}
