
#include "AV.h"
#include "anaglym.h"
#include "Engine.h"
#include "SDL.h"
#include <stdlib.h>                 /* exit(), srand() */
#include <iostream>
#include <string>
using namespace std;

static void usage();

static void usage()
{
    cerr << "Usage: anaglym [options] program.lua[c]" << endl;
    cerr << "Options:" << endl;
    cerr << "  -w<width>  : set window width" << endl;
    cerr << "  -h<height> : set window height" << endl;
    cerr << "  -f         : do not fullscreen" << endl;
    cerr << "  -g         : do not grab mouse input" << endl;
    cerr << "  -s<samples>: set multisample level (default 4)" << endl;
    exit(42);
}

int main(int argc, char * argv[])
{
    bool fullscreen = true;
    bool grab_input = true;
    int width = 0;
    int height = 0;
    int samples = 4;
    const char * program = NULL;
    for (int i = 1; i < argc; i++)
    {
        if (argv[i][0] != '-')
        {
            if (program == NULL)
            {
                program = argv[i];
            }
            else
            {
                cerr << "Warning: argument " << argv[i] << " ignored!" << endl;
                usage();
            }
        }
        else
        {
            if      (!strcmp(argv[i], "-f"))
            {
                fullscreen = false;
            }
            else if (!strcmp(argv[i], "-g"))
            {
                grab_input = false;
            }
            else if (!strncmp(argv[i], "-w", 2))
            {
                width = atoi((strlen(argv[i]) == 2) ? argv[++i] : argv[i] + 2);
            }
            else if (!strncmp(argv[i], "-h", 2))
            {
                height = atoi((strlen(argv[i]) == 2) ? argv[++i] : argv[i] + 2);
            }
            else if (!strncmp(argv[i], "-s", 2))
            {
                samples = atoi((strlen(argv[i]) == 2) ? argv[++i] : argv[i] + 2);
            }
            else
            {
                cerr << "Warning: Unrecognized option '" << argv[i]+1
                     << "'" << endl;
                usage();
            }
        }
    }

    if (program == NULL)
    {
        usage();
    }

    srand(time(NULL));

    AV av;
    if (!av.start(width, height, fullscreen, grab_input, samples))
    {
        cerr << "anaglym: exiting." << endl;
        return -1;
    }

    /* find the full path to the program */
    string engine_path = argv[0];
#ifdef PLATFORM_LINUX
    /* get the full path to the process using /proc/self/exe */
    char * buff = new char[10000];
    ssize_t bytes_read = readlink("/proc/self/exe", buff, 9999);
    if (bytes_read > 0)
    {
        buff[bytes_read] = '\0';
        engine_path = buff;
    }
    delete[] buff;
#endif

    dInitODE();
    g_engine = new Engine(engine_path, av);
    if (g_engine->load(program))
        g_engine->run();
    delete g_engine;
    av.stop();
    dCloseODE();

    return 0;
}
