/* gfortran 4.6 ABI: INTEGER=32 bits, hidden CHARACTER lengths=int32_t.
 * F77 handles index these tables; native 64-bit handles are never truncated.
 * This port, like newlib, is single-threaded. */
#include "../native/gaspardos_x64_syscall.h"
#include <string.h>

#define SLOTS 32

typedef struct
{
    int     used;
    int     ready;
    int64_t native;
} Slot;

static Slot windows[SLOTS], sockets[SLOTS];

static Slot* lookup(Slot* slots, int32_t token)
{
    return token > 0 && token <= SLOTS && slots[token - 1].used ? &slots[token - 1] : NULL;
}

static int available(Slot* slots)
{
    int i;
    for (i = 0; i < SLOTS; ++i)
        if (!slots[i].used)
            return i;
    return -1;
}

static void text_copy(char* out, unsigned capacity, const char* in, int32_t length)
{
    unsigned n = length > 0 ? (unsigned) length : 0;
    while (n && in[n - 1] == ' ')
        --n;
    if (n >= capacity)
        n = capacity - 1;
    memcpy(out, in, n);
    out[n] = 0;
}

static void transfer_result(int64_t r, int32_t* count, int32_t* error)
{
    *count = r >= 0 ? (int32_t) r : 0;
    *error = r < 0 ? (int32_t) r : 0;
}

void gbcwin_(const char*    title,
             const int32_t* width,
             const int32_t* height,
             int32_t*       handle,
             int32_t*       error,
             int32_t        title_length)
{
    int                i = available(windows);
    GO64_WindowOptions options;
    int64_t            r;
    *handle = 0;
    if (i < 0)
    {
        *error = -24;
        return;
    }
    memset(&options, 0, sizeof(options));
    options.width  = *width;
    options.height = *height;
    text_copy(options.title, sizeof(options.title), title, title_length);
    r      = GO64_window_create(&options);
    *error = r < 0 ? (int32_t) r : 0;
    if (r >= 0)
    {
        windows[i].native = r;
        windows[i].used   = 1;
        windows[i].ready  = 0;
        *handle           = i + 1;
    }
}

void gbshow_(const int32_t* handle, int32_t* error)
{
    Slot* s = lookup(windows, *handle);
    *error  = s ? (int32_t) GO64_window_focus(s->native) : -9;
}

void gbwcls_(int32_t* handle, int32_t* error)
{
    Slot* s = lookup(windows, *handle);
    *error  = s ? (int32_t) GO64_window_destroy(s->native) : -9;
    if (*error == 0)
    {
        s->used = 0;
        *handle = 0;
    }
}

/* Event payload is eight INTEGERs, copied rather than type-punned. */
void gbwevt_(const int32_t* handle, const int32_t* mode, int32_t* fields, int32_t* error)
{
    Slot*      s = lookup(windows, *handle);
    GO64_Event event;
    memset(fields, 0, 8 * sizeof(*fields));
    *error = s ? (int32_t) GO64_window_event(s->native, &event, *mode) : -9;
    if (*error == 0)
    {
        memcpy(fields, &event, sizeof(event));
        if (event.type == GO64_READY)
            s->ready = 1;
        if (event.type == GO64_ERROR)
            s->ready = 0;
    }
}

void gbwdraw_(const int32_t* handle,
              const int32_t* x,
              const int32_t* y,
              const int32_t* width,
              const int32_t* height,
              const int32_t* color,
              const char*    text,
              const int32_t* is_text,
              int32_t*       error,
              int32_t        text_length)
{
    Slot*        s = lookup(windows, *handle);
    GO64_Drawing drawing;
    if (!s)
    {
        *error = -9;
        return;
    }
    if (!s->ready)
    {
        *error = -11;
        return;
    }
    memset(&drawing, 0, sizeof(drawing));
    drawing.x      = *x;
    drawing.y      = *y;
    drawing.width  = *width;
    drawing.height = *height;
    drawing.color  = (uint32_t) *color;
    text_copy(drawing.text, sizeof(drawing.text), text, text_length);
    *error = (int32_t) (*is_text ? GO64_window_text(s->native, &drawing)
                                 : GO64_window_fill(s->native, &drawing));
}

void gbsock_(const int32_t* family,
             const int32_t* type,
             const int32_t* protocol,
             int32_t*       handle,
             int32_t*       error)
{
    int     i = available(sockets);
    int64_t r;
    *handle = 0;
    if (i < 0)
    {
        *error = -24;
        return;
    }
    r      = GO64_socket(*family, *type, *protocol);
    *error = r < 0 ? (int32_t) r : 0;
    if (r >= 0)
    {
        sockets[i].native = r;
        sockets[i].used   = 1;
        *handle           = i + 1;
    }
}

static int address_parse(const char* host, int32_t length, int32_t port, GO64_SocketAddress* a)
{
    int            part;
    int32_t        pos   = 0;
    unsigned char* bytes = (unsigned char*) &a->port;
    if (port < 0 || port > 65535 || length <= 0)
        return -22;
    a->family = GO64_AF_INET;
    bytes[0]  = (unsigned char) (port >> 8);
    bytes[1]  = (unsigned char) port;
    while (length > 0 && host[length - 1] == ' ')
        --length;
    for (part = 0; part < 4; ++part)
    {
        unsigned value  = 0;
        int      digits = 0;
        while (pos < length && host[pos] >= '0' && host[pos] <= '9')
        {
            value = value * 10 + (unsigned) (host[pos++] - '0');
            if (++digits > 3 || value > 255)
                return -22;
        }
        if (!digits)
            return -22;
        a->address[part] = (uint8_t) value;
        if (part < 3 && (pos >= length || host[pos++] != '.'))
            return -22;
    }
    return pos == length ? 0 : -22;
}

void gbconn_(const int32_t* handle,
             const char*    host,
             const int32_t* port,
             int32_t*       error,
             int32_t        host_length)
{
    Slot*              s = lookup(sockets, *handle);
    GO64_SocketAddress address;
    *error = s ? address_parse(host, host_length, *port, &address) : -9;
    if (*error == 0)
        *error = (int32_t) GO64_connect(s->native, &address, sizeof(address));
}

void gbsend_(const int32_t* handle,
             const char*    data,
             const int32_t* size,
             int32_t*       count,
             int32_t*       error,
             int32_t        data_length)
{
    Slot* s = lookup(sockets, *handle);
    if (*size < 0 || *size > data_length)
    {
        *count = 0;
        *error = -22;
        return;
    }
    transfer_result(s ? GO64_send(s->native, data, *size, 0) : -9, count, error);
}

void gbrecv_(const int32_t* handle,
             char*          data,
             const int32_t* size,
             int32_t*       count,
             int32_t*       error,
             int32_t        data_length)
{
    Slot* s = lookup(sockets, *handle);
    if (*size < 0 || *size > data_length)
    {
        *count = 0;
        *error = -22;
        return;
    }
    transfer_result(s ? GO64_recv(s->native, data, *size, 0) : -9, count, error);
}

void gbscls_(int32_t* handle, int32_t* error)
{
    Slot* s = lookup(sockets, *handle);
    *error  = s ? (int32_t) GO64_socket_close(s->native) : -9;
    if (*error == 0)
    {
        s->used = 0;
        *handle = 0;
    }
}

void gbyield_(void)
{
    (void) GO64_yield();
}
