#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>    // _O_BINARY for Win32
#include <getopt.h>
#include <signal.h>
#include <sys/types.h>

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

#include <sc/sc.h>
#include "sce.h"
#include "cpu.h"
#include "debug.h"
#include "memory.h"
#include "sctrl.h"
#include "cif.h"
#include "aes.h"
#include "sha.h"
#include "fl.h"
#include "aud.h"
#include "usb.h"

static int halted;
int systemRV = 0;

char *boot_bdoor;
char *da_bdoor;
char *sdram_bdoor;
char *os_bdoor;
int debug_port;
bool mem_flip;
u32 default_tag = 0;
SOCKET usbSocket = 0;
u32 cifSlowdown = 0;
u32 exitOnError = 1;
char *cmdlineArgs = NULL;
u32 boardID = 0;
u32 flashSize = 2048;
u32 watchpoint = 0;
u32 flashInit = 0;
char *audioIn = NULL;
char *audioOut = NULL;

void sigquit(int a)
{
    log(LOG_SYSTEM, "Caught signal!\n");
    halted = 1;
}


ProcessorContext proc[2];
int currentCpu;

#ifdef _WIN32
static int WSAInit()
{
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;
 
    wVersionRequested = MAKEWORD( 2, 2 );
 
    err = WSAStartup( wVersionRequested, &wsaData );
    if ( err != 0 ) {
        /* Tell the user that we could not find a usable */
        /* WinSock DLL.                                  */
        fprintf(stderr, "can't start winsock library\n");
        return -1;
    }
 
    /* Confirm that the WinSock DLL supports 2.2.*/
    /* Note that if the DLL supports versions greater    */
    /* than 2.2 in addition to 2.2, it will still return */
    /* 2.2 in wVersion since that is the version we      */
    /* requested.                                        */
    
    if ( LOBYTE( wsaData.wVersion ) != 2 ||
         HIBYTE( wsaData.wVersion ) != 2 ) {
        /* Tell the user that we could not find a usable */
        /* WinSock DLL */
        fprintf(stderr, "winsock version is not >= 2.2\n");
        WSACleanup( );
        return -1; 
    }
    return 0;
}
#endif


void systemInit(void)
{
#ifndef _WIN32  // Win32 has no SIGQUIT
    signal(SIGQUIT, sigquit);
#endif
    signal(SIGINT, sigquit);

    if (debug_port) debugInit(debug_port);
    cpuInit(&proc[0]);
    cpuInit(&proc[1]);
    memoryInit(boot_bdoor, da_bdoor, sdram_bdoor, os_bdoor);
    sysInit();
    cifInit();
    aesInit();
    shaInit();
    flInit();
    audInit();
    usbInit();
}

void systemReset(int soft=0)
{
    cpuReset(&proc[0]);
    cpuReset(&proc[1]);
    memoryReset();
    sysReset(soft);
    cifReset();
    aesReset();
    shaReset();
    flReset();
    audReset();
    usbReset();
}

void systemLoop(void)
{
    while (!halted) {
        for (int i = 0; i < 2; ++i) {
            currentCpu = i;
            if (SYS_SMP_SMP_RST(sys.smp[i]) == 0) {
                if (debug_port && i == 0) {
                    debugTick(&proc[i]);
                } else {
                    cpuTick(&proc[i]);
                }
            }
        }

        u32 pending = 0;

        if (aesTick()) pending |= SYS_AES_INTR;
        if (shaTick()) pending |= SYS_SHA_INTR;
        if (flTick()) pending |= SYS_FLASH_INTR;
        if (audTick()) pending |= SYS_AUD_INTR;
        if (cifTick()) pending |= SYS_CIF_INTR;
        if (sysTick()) pending |= SYS_SYS_INTR;

        sys.smp[0] &= ~SYS_SMP_IPEND_MASK;
        sys.smp[1] &= ~SYS_SMP_IPEND_MASK;
        sys.smp[0] |= (pending << SYS_SMP_IPEND_SHIFT);
        sys.smp[1] |= (pending << SYS_SMP_IPEND_SHIFT);

        if (__needsReset) {
            __needsReset = 0;
            systemReset(1);
        }
    }
}

void systemShutdown(void)
{
    log(LOG_SYSTEM, "Shutting down...\n");

    cpuShutdown(&proc[0]);
    cpuShutdown(&proc[1]);
    memoryShutdown();
    sysShutdown();
    aesShutdown();
    shaShutdown();
    flShutdown();
    audShutdown();
    usbShutdown();
    cifShutdown();
}

void Usage(char *prog)
{
    fprintf(stderr, "Usage: %s [options]\n", prog);
    fprintf(stderr, "SC hardware emulator\n\n");
    fprintf(stderr, "-a, --args <cmdline args>\tPass command-line args to code running on simulator\n");
    fprintf(stderr, "    --boardid <id>\tSet board id to <id>\n");
    fprintf(stderr, "-b, --boot <image>\tPreload boot ROM with <image>\n");
    fprintf(stderr, "-c, --cram <image>\tPreload cram with <image>\n");
    fprintf(stderr, "-e, --exit\tExit on 1st error message\n");
    fprintf(stderr, "-f, --flip\t\tFlip BOOT and DA\n");
    fprintf(stderr, "    --flash <size>\tSize of flash page (512 or 2048)\n");
    fprintf(stderr, "    --flashinit\t\tInitialize flash to all 0xff\n");
    fprintf(stderr, "-g, --gdb <port>\tEnable gdb remote debugging on <port>\n");
    fprintf(stderr, "-l, --log <filename>\tSend log messages to <filename>\n");
    fprintf(stderr, "-o, --os <image>\tPreload OS from <image>\n");
    fprintf(stderr, "-s, --sdram <image>\tPreload SDRAM with <image>\n");
    fprintf(stderr, "-t, --tags <tag>\tBlock fill tag memory with <tag>\n");
    fprintf(stderr, "-u, --usbhack <host>:<port>\tConnect to server at <host>:<port> to do usb hack\n");
    fprintf(stderr, "-v, --verbose <level>\tTurn on verbose output\n");
    map<string, LogLevel>::iterator i;
    for (i = logLevels.begin(); i != logLevels.end(); ++i) {
        fprintf(stderr, "                     \t  %s - %s\n", i->first.c_str(), i->second.description);
    }
    fprintf(stderr, "-w, --watch <addr>\tWatch for change in value @ DA address\n");
    fprintf(stderr, "-h, --help\t\tDisplay this help and exit\n");
}

int main(int argc, char *argv[])
{
    char short_options[] = "ha:b:c:efg::k:l:o:p:s:t:u:v:w:";

#ifndef _WIN32
    static struct option long_options[] = {
        {"help", 0, 0, 'h'},
        {"audioIn", 1, 0, 0},
        {"audioOut", 1, 0, 0},
        {"args", 1, 0, 'a'},
        {"boot", 1, 0, 'b'},
        {"cram", 1, 0, 'c'},
        {"boardid", 1, 0, 0},
        {"cram", 1, 0, 'c'},
        {"os", 1, 0, 'o'},
        {"exit", 0, 0, 'e'},
        {"flip", 0, 0, 'f'},
        {"flash", 1, 0, 0},
        {"gdb", 2, 0, 'g'},
        {"log", 1, 0, 'l'},
        {"sdram", 1, 0, 's'},
        {"slowdown", 1, 0, 0},
        {"tags", 1, 0, 't'},
        {"usbhack", 1, 0, 'u'},
        {"verbose", 1, 0, 'v'},
        {"watch", 1, 0, 'w'},
        {"flashinit", 0, 0, 0},
        {0, 0, 0, 0}
    };
#endif

#ifdef _WIN32
    // open files in binary mode 
    _fmode = _O_BINARY;

    // Initialize WinSock2
    if (WSAInit() != 0) exit(-1); 
#endif

    logInit();

    while (1) {
        int option_index = 0;

#ifdef _WIN32
        int c = getopt(argc, argv, short_options);
#else
        int c = getopt_long(argc, argv, short_options, long_options, &option_index);
#endif
        if (c == -1)
            break;
        switch (c) {
#ifndef _WIN32
        case 0:
            if (!strcmp(long_options[option_index].name, "slowdown")) {
                cifSlowdown = strtoul(optarg, NULL, 0);
            } else if (!strcmp(long_options[option_index].name, "audioIn")) {
                audioIn = optarg;
            } else if (!strcmp(long_options[option_index].name, "audioOut")) {
                audioOut = optarg;
            } else if (!strcmp(long_options[option_index].name, "boardid")) {
                boardID = strtoul(optarg, NULL, 0);
            } else if (!strcmp(long_options[option_index].name, "flash")) {
                flashSize = strtoul(optarg, NULL, 0);
            } else if (!strcmp(long_options[option_index].name, "flashinit")) {
                flashInit = 1;
            }
            break;
#endif
        case 'h':
            Usage(argv[0]);
            return 0;
        case 'a':
            cmdlineArgs = optarg;
            break;
        case 'b':
            boot_bdoor = optarg;
            break;
        case 'c':
            da_bdoor = optarg;
            break;
        case 'o':
            os_bdoor = optarg;
            break;
        case 'e':
            exitOnError = !exitOnError;
            break;
        case 'f':
            mem_flip = !mem_flip;
            break;
        case 'g':
            if (optarg) {
                debug_port = strtoul(optarg, NULL, 0);
            } else {
                debug_port = 1114;
            }
            break;
        case 's':
            sdram_bdoor = optarg;
            break;
        case 't':
            default_tag = strtoul(optarg, NULL, 0);
            break;
        case 'l':
            logSetOutput(optarg);
            break;
        case 'u': {
            char *p;

            if ((p = strchr(optarg, ':'))) {
                char *host;
                u32 port;
                struct hostent *hostent;
                struct sockaddr_in sockaddr;

                *p++ = 0;
                host = optarg;
                port = strtoul(p, NULL, 0);
                if (!host[0]) host = "localhost";
                if (!(hostent = gethostbyname(host))) {
#ifdef _WIN32
                    int winsockerr = WSAGetLastError();
                    fprintf(stderr, "gethostbyname: %d\n", winsockerr);
#endif
                    fprintf(stderr, "Unknown host: '%s'\n", host);
                    return -1;
                }
                if ((usbSocket = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
                    perror("socket");
                    return -1;
                }
                sockaddr.sin_family = PF_INET;
                sockaddr.sin_port = htons(port);
                memcpy(&sockaddr.sin_addr.s_addr, hostent->h_addr, sizeof(struct in_addr));
                if (connect(usbSocket,(struct sockaddr*) &sockaddr, sizeof(sockaddr)) < 0) {
                    perror("connect");
                    return -1;
                }
            } else {
                Usage(argv[0]);
                return -1;
            }
            break;
        }
        case 'v':
            logSetLevel(optarg);
            break;
        case 'w':
            watchpoint = strtoul(optarg, NULL, 0);
            break;
        default:
            fprintf(stderr, "Unrecognized option '%c'\n", c);
            return -1;
        }
 
    }

    systemInit();
    systemReset();
    systemLoop();
    systemShutdown();
    
#ifdef _WIN32
    WSACleanup();
#endif

    return systemRV;
}

