#ifdef _WIN32
#include <Winsock2.h>
#include <io.h>
#else
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

#include <signal.h>

#include "sc/sc.h"
#include "sce.h"
#include "sctrl.h"
#include "memory.h"
#include "cpu.h"
#include "log.h"
#include "debug.h"

static SOCKET lsock = -1;
static SOCKET sock = -1;

static int resumed;
static int debugging;

void debugPutPacket(char *packet)
{
    char *hex = "0123456789abcdef";
    char buffer[1024];

    int count = (int) strlen(packet);

    unsigned char csum = 0;

    char *p = buffer;
    *p++ = '$';

    for(int i = 0 ;i < count; i++) {
        csum += packet[i];
        *p++ = packet[i];
    }
    *p++ = '#';
    *p++ = hex[csum>>4];
    *p++ = hex[csum & 15];
    *p++ = 0;
    send(sock, buffer, count + 4, 0);

    char c = 0;
    recv(sock, &c, 1, 0);
}


static int checkSock(void)
{
    int rv;
    struct timeval tv;
    fd_set rfds;
    FD_ZERO(&rfds);
    FD_SET(sock, &rfds);
    memset(&tv, 0, sizeof(tv));
    rv = select((int)sock+1, &rfds, NULL, NULL, &tv);
    return rv;
}

static int debugGetCh(void)
{
    char c;
    recv(sock, &c, sizeof(c), 0);
    return c;
}

static void debugPutCh(char c)
{
    send(sock, &c, sizeof(c), 0);
}

static int hex_to_int (char h)
{
    if (h >= 'a' && h <= 'f') return h - 'a' + 10;
    if (h >= '0' && h <= '9') return h - '0';
    if (h >= 'A' && h <= 'F') return h - 'A' + 10;
    return 0;
}

static int debugGetMsg(char *rxbuf)
{
    char c;
    unsigned char sum;
    unsigned char rx_sum;
    char *buf;

get_msg:
    /* wait around for start character, ignore all others */
    while (debugGetCh() != '$');

    /* start counting bytes */
    buf = rxbuf;
    sum = 0;

    /* read until we see the '#' at the end of the packet */
    do {
        *buf++ = c = debugGetCh();
        if (c != '#') sum += c;

        /* since the buffer is ascii, may as well terminate it */
        *buf = 0;

    } while (c != '#');

    /* receive checksum */
    rx_sum = hex_to_int(debugGetCh());
    rx_sum = (rx_sum << 4) + hex_to_int(debugGetCh());

    /* if computed checksum doesn't match received checksum, then reject */
    if (sum != rx_sum) {
        debugPutCh('-');
        goto get_msg;
    } else {
        debugPutCh('+');
    }

    log(LOG_DEBUG, "DEBUG: recv '%s'\n", rxbuf);

    return 1;
}

static int debugSignal = 5;

void debugReadRegisters(ProcessorContext *p)
{
    char buffer[1024];

    char *s = buffer;
    int i;
    // regular registers
    for(i = 0; i < 15; i++) {
        sprintf(s, "%08x", (u32)htonl(p->reg[i].I));
        s += 8;
    }
    // PC
    sprintf(s, "%08x", (u32)htonl(p->nextPC));
    s += 8;

    // floating point registers (24-bit)
    for(i = 0; i < 8; i++) {
        sprintf(s, "000000000000000000000000");
        s += 24;
    }
    // FP status register
    sprintf(s, "00000000");
    s += 8;

    // CPSR
    CPUUpdateCPSR(p);
    sprintf(s, "%08x", (u32)htonl(p->reg[16].I));
    s += 8;
    *s = 0;
    debugPutPacket(buffer);
}

void debugReadRegister(ProcessorContext *p, char *cmd)
{
    char buffer[16];
    char *s = buffer;
    int reg = hex_to_int(*cmd);
    sprintf(s, "%08x", (u32)htonl(reg != 15 ? p->reg[reg].I : p->nextPC));
    s += 8;
    *s = 0;
    debugPutPacket(buffer);
    log(LOG_DEBUG, "Read register %d [%08x]\n", hex_to_int(*cmd), p->reg[hex_to_int(*cmd)]);
}

void debugSendSignal(void)
{
    char buffer[16];
#ifdef _WIN32  // Win32 does not provide snprintf() 
    sprintf(buffer, "S%02x", debugSignal);
#else
    snprintf(buffer, sizeof(buffer), "S%02x", debugSignal);
#endif
    debugPutPacket(buffer);
}

void debugSendStatus(ProcessorContext *p)
{
    char buffer[1024];
#ifdef _WIN32  // Win32 does not provide snprintf()
    sprintf(buffer, "T%02x", debugSignal);
#else
    snprintf(buffer, sizeof(buffer), "T%02x", debugSignal);
#endif

    char *s = buffer;
    s += 3;
    int i;
    // regular registers
    for(i = 0; i < 15; i++) {
        sprintf(s, "%02x:%08x;", i, (u32)htonl(p->reg[i].I));
        s += 12;
    }
    // PC
    sprintf(s, "0f:%08x;", (u32)htonl(p->nextPC));
    s += 12;

    // CPSR
    CPUUpdateCPSR(p);
    sprintf(s, "19:%08x;", (u32)htonl(p->reg[16].I));
    s += 12;
    *s = 0;

    log(LOG_DEBUG, "send status = '%s'\n", buffer);
    debugPutPacket(buffer);
}

void debugBreakpoint(ProcessorContext *p)
{
    resumed = 0;
    debugSendStatus(p);
}

void debugReadMemory(ProcessorContext *p, char *c)
{
    u32 address, count;
    sscanf(c, "%x,%x:", &address, &count);

    char buffer[1024];
    char *s = buffer;
    u8 b;
    for (u32 i=0; i < count; ++i) {
        if (SCMemoryAccess(MEMORY_SRC_DBG, DEBUG_TID, p->mode, address++, &b, sizeof(b), MEMORY_READ, NULL, NULL) < 0) {
            goto error;
        }
        sprintf(s, "%02x", b);
        s += 2;
    }
    *s = '\0';
    debugPutPacket(buffer);
    return;
error:
    debugPutPacket("E00");
}

void debugWriteMemory(ProcessorContext *p, char *c)
{
    u32 address;
    u32 count;
    sscanf(c,"%x,%x:", &address, &count);

    c = strchr(c, ':');
    c++;
    for(u32 i = 0; i < count; i++) {
        u8 v = 0;
        char d = *c++;
        if(d <= '9')
            v = (d - '0') << 4;
        else
            v = (d + 10 - 'a') << 4;
        d = *c++;
        if(d <= '9')
            v += (d - '0');
        else
            v += (d + 10 - 'a');
        if (SCMemoryAccess(MEMORY_SRC_DBG, DEBUG_TID, p->mode, address++, &v, sizeof(v), MEMORY_WRITE, NULL, NULL) < 0) {
            goto error;
        }
    }

    debugPutPacket("OK");
    return;
error:
    debugPutPacket("E00");
}

void debugBinaryWriteMemory(ProcessorContext *p, char *c)
{
    u32 address;
    u32 count;
    sscanf(c,"%x,%x:", &address, &count);

    c = strchr(c, ':');
    c++;
    for(u32 i = 0; i < count; i++) {
        u8 b = *c++;
        if (b == 0x7d) {
            b = (*c++) ^ 0x20;
        }
        if (SCMemoryAccess(MEMORY_SRC_DBG, DEBUG_TID, p->mode, address++, &b, sizeof(b), MEMORY_WRITE, NULL, NULL) < 0) {
            goto error;
        }
    }
    
    debugPutPacket("OK");
    return;
error:
    debugPutPacket("E00");
}


#define CONTINUE 1
#define STEP     2
void debugTick(ProcessorContext *p)
{

    if (!debugging) {
        return;
    }

    while (!resumed) {
        char buffer[1024];
        char *c;

        debugGetMsg(buffer);
        c = buffer;
        switch (*c++) {
        case '?':
            debugSendSignal();
            break;
        case 'g':
            debugReadRegisters(p);
            break;
        case 'p':
            debugReadRegister(p, c);
            break;
        case 'H':
            debugPutPacket("OK");
            break;
        case 'm':
            debugReadMemory(p, c);
            break;
        case 'M':
            debugWriteMemory(p, c);
            break;
        case 'X':
            debugBinaryWriteMemory(p, c);
            break;
        case 'c':
            resumed = CONTINUE;
            break;
        case 's':
            resumed = STEP;
            break;
        case 'q':
        case 'v':
            debugPutPacket("");
            break;
        default:
            *(strchr(c, '#') + 3) = 0;
            log(LOG_DEBUG, "Unknown packet %s\n", --c);
            debugPutPacket("");
            break;
        }
    }
    cpuTick(p);
    if (resumed == STEP) {
        resumed = 0;
        debugSendSignal();
    } else {
        if (checkSock()) resumed = STEP;
    }
}

void debugShutdown(void)
{
    if (sock > 0) {
        log(LOG_DEBUG, "Closing remote socket\n");
        close(sock);
        sock = -1;
    }
    if (lsock > 0) {
        log(LOG_DEBUG, "Closing listen socket\n");
        close(lsock);
        lsock = -1;
    }
}

int debugInit(int port)
{
    if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
        return -1;
    }
    int tmp = 1;
    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &tmp, sizeof (tmp));

    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = htonl(0);
    if(bind(sock, (sockaddr *)&addr, sizeof(addr))) {
        return -1;
    }

    log(LOG_DEBUG, "Listening for a connection at port %d\n",
            ntohs(addr.sin_port));

    if(listen(sock, 1)) {
        return -1;
    }
    socklen_t len = sizeof(addr);

    sock = accept(sock, (sockaddr *)&addr, &len);
    if(sock > 0) {
        log(LOG_DEBUG, "Got a connection from %s %d\n",
            inet_ntoa((in_addr)addr.sin_addr),
            ntohs(addr.sin_port));
    }

    debugging = 1;

    return 0;
}
