#include "InterpreterV8.h"

#ifdef HAVE_V8

#include <fstream>
#include <sstream>
#include <iomanip>

#include <boost/tokenizer.hpp>

#ifdef HAVE_NOVA
#include <libnova/lunar.h>
#include <libnova/transform.h>
#endif

#ifdef HAVE_SQL
#include "Database.h"
#endif

#include <v8.h>

#include "tools.h"

using namespace std;
using namespace v8;


// ==========================================================================
//                           Some documentation
// ==========================================================================
//
// Threads:
// --------
// In most cases Js* and other calls to native C++ code could be wrapped
// with an Unlocker to allow possible other JavaScipt 'threads' to run
// during that time. However, all of these calls should take much less than
// the preemption time of 10ms, so it would just be a waste of tim.
//
// Termination:
// ------------
// Each thread running V8 code needs to be signalled individually for
// termination. Therefor a list of V8 thread ids is created.
//
// If termination has already be signalled, no thread should start running
// anymore (thy could, e.g., wait for their locking). So after locking
// it has to be checked if the thread was terminated already. Note
// that all calls to Terminate() must be locked to ensure that fThreadId
// is correct when it is checked.
//
// The current thread id must be added to fThreadIds _before_ any
// function is called after Locking and before execution is given
// back to JavaScript, e.g. in script->Run(). So until the thread
// is added to the list Terminate will not be executed. If Terminate
// is then executed, it is ensured that the current thread is
// already in the list. If terminate has been called before
// the Locking, the check for the validiy of fThreadId ensures that
// nothing is executed.
//
// Empty handles:
// --------------
// If exceution is terminated, V8 calls might return with empty handles,
// e.g. Date::New(). Therefore, the returned handles of these calls have to
// be checked in all placed to avoid that V8 will core dump.
//
// HandleScope:
// ------------
// A handle scope is a garbage collector and collects all handles created
// until it goes out of scope. Handles which are not needed anymore are
// then deleted. To return a handle from a HandleScope you need to use
// Close(). E.g., String::Utf8Value does not create a new handle and
// hence does not need a HandleScope. Any ::New will need a handle scope.
// Forgetting the HandleScope could in principle fill your memory,
// but everything is properly deleted by the global HandleScope at
// script termination.
//

// ==========================================================================
//                            Simple interface
// ==========================================================================

void InterpreterV8::Terminate()
{
    if (!Locker::IsLocked())
        JsException("***** InterprterV8::Terminate call not locked *****");

    for (auto it=fThreadIds.begin(); it!=fThreadIds.end(); it++)
        V8::TerminateExecution(*it);
    fThreadIds.clear();

    if (fThreadId>=0)
    {
        V8::TerminateExecution(fThreadId);
        fThreadId = -1;
    }
}

Handle<Value> InterpreterV8::FuncExit(const Arguments &)
{
    Terminate();
    return ThrowException(String::New("exit"));
}

Handle<Value> InterpreterV8::FuncSleep(const Arguments& args)
{
    if (args.Length()==0)
    {
        // Theoretically, the CPU usage can be reduced by maybe a factor
        // of four using a larger value, but this also means that the
        // JavaScript is locked for a longer time.
        const Unlocker unlock;
        usleep(1000);
        return Undefined();
    }

    if (args.Length()!=1)
        return ThrowException(String::New("Number of arguments must be exactly 1."));

    if (!args[0]->IsUint32())
        return ThrowException(String::New("Argument 1 must be an uint32."));

    // Using a Javascript function has the advantage that it is fully
    // interruptable without the need of C++ code
    const string code =
        "(function(){"
        "var t=new Date();"
        "while ((new Date()-t)<"+to_string(args[0]->Int32Value())+") dim.sleep();"
        "})();";

    return ExecuteInternal(code);
}

void InterpreterV8::ThreadTimeout(Persistent<Function> func, uint32_t ms)
{
    const Locker lock;

    if (fThreadId<0)
        return;

    const int id = V8::GetCurrentThreadId();
    fThreadIds.insert(id);

    const HandleScope handle_scope;

    fGlobalContext->Enter();

    TryCatch exception;

    const bool rc = ms==0 || !ExecuteInternal("dim.sleep("+to_string(ms)+");").IsEmpty();
    if (rc)
    {
        Handle<Value> args[] = {  };
        func->Call(func, 0, args);
    }

    func.Dispose();
    fThreadIds.erase(id);

    if (!exception.HasCaught())
        return;

    ReportException(&exception);
    Terminate();
}

Handle<Value> InterpreterV8::FuncTimeout(const Arguments& args)
{
    if (args.Length()!=2)
        return ThrowException(String::New("Number of arguments must be at least 1."));

    if (args.Length()==0)
        return ThrowException(String::New("Number of arguments must be at least 1."));

    if (!args[1]->IsFunction())
        return ThrowException(String::New("Argument 1 not a function."));

    if (!args[0]->IsUint32())
        return ThrowException(String::New("Argument 0 not an uint32."));

    const HandleScope handle_scope;

    Handle<Function> handle = Handle<Function>::Cast(args[1]);

    Persistent<Function> func = Persistent<Function>::New(handle);

    const uint32_t ms = args[0]->Uint32Value();

    fTimeout.push_back(thread(bind(&InterpreterV8::ThreadTimeout, this, func, ms)));
    return Undefined();
}

Handle<Value> InterpreterV8::FuncSend(const Arguments& args)
{
    if (args.Length()==0)
        return ThrowException(String::New("Number of arguments must be at least 1."));

    if (!args[0]->IsString())
        return ThrowException(String::New("Argument 1 must be a string."));

    const String::Utf8Value str(args[0]);

    string command = *str;

    // Escape all string arguments. All others can be kept as they are.
    for (int i=1; i<args.Length(); i++)
    {
        const String::Utf8Value arg(args[i]);
        if (args[i]->IsString())
            command += " \""+string(*arg)+"\"";
        else
            command += " "+string(*arg);
    }

    return Boolean::New(JsSend(command));
}

// ==========================================================================
//                               State control
// ==========================================================================

Handle<Value> InterpreterV8::FuncWait(const Arguments& args)
{
    if (args.Length()!=2 && args.Length()!=3)
        return ThrowException(String::New("Number of arguments must be 2 or 3."));

    if (!args[0]->IsString())
        return ThrowException(String::New("Argument 1 not a string."));

    if (!args[1]->IsInt32() && !args[1]->IsString())
        return ThrowException(String::New("Argument 2 not an int32 and not a string."));

    if (args.Length()==3 && !args[2]->IsUint32())
        return ThrowException(String::New("Argument 3 not an uint32."));

    // Using a Javascript function has the advantage that it is fully
    // interruptable without the need of C++ code

    const string index   = args[1]->IsInt32() ? "s.index" : "s.name";
    const bool   timeout = args.Length()==3;
    const string arg0    = *String::Utf8Value(args[0]);
    const string state   = args[1]->IsString() ? *String::Utf8Value(args[1]) : "";
    const string arg1    = args[1]->IsString() ? ("\""+state+"\"") : to_string(args[1]->Int32Value());

    if (arg0.find_first_of("\"'")!=string::npos)
        return ThrowException(String::New("Server name must not contain quotation marks."));

    if (args[1]->IsString())
        if (state.find_first_of("\"'")!=string::npos)
            return ThrowException(String::New("State name must not contain quotation marks."));

    string code =  "(function(name,state,ms)"
                   "{";
    if (timeout)
        code +=       "var t = new Date();";
    code +=           "while (1)"
                      "{"
                         "var s = dim.state(name);"
                         "if(!"+index+")throw new Error('Waitig for state "+arg1+" of server "+arg0+" failed.');"
                         "if(state=="+index+")return true;";
    if (timeout)
        code +=          "if((new Date()-t)>ms)return false;";

    code +=              "dim.sleep();"
                      "}"
                   "})('"+arg0+"',"+arg1;
    if (timeout)
        code +=    "," + to_string(args[2]->Int32Value());
    code +=        ");";

    return ExecuteInternal(code);
}

Handle<Value> InterpreterV8::FuncState(const Arguments& args)
{
    if (args.Length()!=1)
        return ThrowException(String::New("Number of arguments must be exactly 1."));

    if (!args[0]->IsString())
        return ThrowException(String::New("Argument 1 must be a string."));

    // Return state.name/state.index

    const String::Utf8Value str(args[0]);

    const State rc = JsState(*str);

    //if (rc.first<=-256)
    //    return Undefined();

    HandleScope handle_scope;

    Handle<ObjectTemplate> obj = ObjectTemplate::New();
    obj->Set(String::New("index"), rc.index<=-256?Undefined():Integer::New(rc.index),       ReadOnly);
    obj->Set(String::New("name"),  rc.index<=-256?Undefined():String::New(rc.name.c_str()), ReadOnly);

    const Local<Value> date = Date::New(rc.time.JavaDate());
    if (rc.index>-256 && !date.IsEmpty())
        obj->Set(String::New("time"),  date);

    //obj->Set(String::New("toString"),  String::New(("[Object state "+string(*str)+":"+to_string(rc.index)+"]").c_str()));

    return handle_scope.Close(obj->NewInstance());
}

Handle<Value> InterpreterV8::FuncNewState(const Arguments& args)
{
    if (args.Length()<1 || args.Length()>3)
        return ThrowException(String::New("Number of arguments must be 1, 2 or 3."));

    if (!args[0]->IsUint32())
        return ThrowException(String::New("Argument 1 must be an uint32."));
    if (args.Length()>1 && !args[1]->IsString())
        return ThrowException(String::New("Argument 2 must be a string."));
    if (args.Length()>2 && !args[2]->IsString())
        return ThrowException(String::New("Argument 3 must be a string."));

    const uint32_t index   = args[0]->Int32Value();
    const string   name    = *String::Utf8Value(args[1]);
    const string   comment = *String::Utf8Value(args[2]);

    if (index<10 || index>255)
        return ThrowException(String::New("State must be in the range [10, 255]."));

    if (name.empty())
        return ThrowException(String::New("State name must not be empty."));

    if (name.find_first_of(':')!=string::npos || name.find_first_of('=')!=string::npos)
        return ThrowException(String::New("State name must not contain : or =."));

    if (JsHasState(index) || JsHasState(name))
    {
        const string what =
            "State index ["+to_string(index)+"] or name ["+name+"] already defined.";

        return ThrowException(String::New(what.c_str()));
    }

    return Boolean::New(JsNewState(index, name, comment));
}

Handle<Value> InterpreterV8::FuncSetState(const Arguments& args)
{
    if (args.Length()!=1)
        return ThrowException(String::New("Number of arguments must be exactly 1."));

    if (!args[0]->IsUint32() && !args[0]->IsString())
        return ThrowException(String::New("Argument must be an unint32 or a  string."));

    int index = -2;
    if (args[0]->IsUint32())
    {
        index = args[0]->Int32Value();
    }
    else
    {
        const string name = *String::Utf8Value(args[0]);
        index = JsGetState(name);
        if (index==-2)
            return ThrowException(String::New(("State '"+name+"' not found.").c_str()));
    }

    if (index<10 || index>255)
        return ThrowException(String::New("State must be in the range [10, 255]."));

    return Boolean::New(JsSetState(index));
}

// ==========================================================================
//                             Internal functions
// ==========================================================================


// The callback that is invoked by v8 whenever the JavaScript 'print'
// function is called.  Prints its arguments on stdout separated by
// spaces and ending with a newline.
Handle<Value> InterpreterV8::FuncPrint(const Arguments& args)
{
    for (int i=0; i<args.Length(); i++)
    {
        const String::Utf8Value str(args[i]);
        if (*str)
            JsPrint(*str);
    }
    return Undefined();
}

Handle<Value> InterpreterV8::FuncAlarm(const Arguments& args)
{
    for (int i=0; i<args.Length(); i++)
    {
        const String::Utf8Value str(args[i]);
        if (*str)
            JsAlarm(*str);
    }

    if (args.Length()==0)
        JsAlarm();

    return Undefined();
}

Handle<Value> InterpreterV8::FuncOut(const Arguments& args)
{
    for (int i=0; i<args.Length(); i++)
    {
        const String::Utf8Value str(args[i]);
        if (*str)
            JsOut(*str);
    }
    return Undefined();
}

// The callback that is invoked by v8 whenever the JavaScript 'load'
// function is called.  Loads, compiles and executes its argument
// JavaScript file.
Handle<Value> InterpreterV8::FuncInclude(const Arguments& args)
{
    for (int i=0; i<args.Length(); i++)
    {
        const String::Utf8Value file(args[i]);
        if (*file == NULL)
            return ThrowException(String::New("File name missing"));

        if (!ExecuteFile(*file))
            return Boolean::New(false);
    }
    return Boolean::New(true);
}

Handle<Value> InterpreterV8::FuncVersion(const Arguments&)
{
    return String::New(V8::GetVersion());
}

// ==========================================================================
//                                 Database
// ==========================================================================

Handle<Value> InterpreterV8::FuncDbClose(const Arguments &args)
{
    void *ptr = External::Unwrap(args.This()->GetInternalField(0));
    if (!ptr)
        return Boolean::New(false);

#ifdef HAVE_SQL
    Database *db = reinterpret_cast<Database*>(ptr);
    auto it = find(fDatabases.begin(), fDatabases.end(), db);
    fDatabases.erase(it);
    delete db;
#endif

    HandleScope handle_scope;

    args.This()->SetInternalField(0, External::New(0));

    return handle_scope.Close(Boolean::New(true));
}
Handle<Value> InterpreterV8::FuncDbQuery(const Arguments &args)
{
    if (args.Length()==0)
        return ThrowException(String::New("Arguments expected."));

    void *ptr = External::Unwrap(args.This()->GetInternalField(0));
    if (!ptr)
        return Undefined();

    string query;
    for (int i=0; i<args.Length(); i++)
        query += string(" ") + *String::Utf8Value(args[i]);
    query.erase(0, 1);

#ifdef HAVE_SQL
    try
    {
        HandleScope handle_scope;

        Database *db = reinterpret_cast<Database*>(ptr);

        const mysqlpp::StoreQueryResult res = db->query(query).store();

        Handle<Array> ret = Array::New();
        if (ret.IsEmpty())
            return Undefined();

        ret->Set(String::New("table"), String::New(res.table()),   ReadOnly);
        ret->Set(String::New("query"), String::New(query.c_str()), ReadOnly);

        Handle<Array> cols = Array::New();
        if (cols.IsEmpty())
            return Undefined();

        int irow=0;
        for (vector<mysqlpp::Row>::const_iterator it=res.begin(); it<res.end(); it++)
        {
            Handle<Array> row = Array::New();
            if (row.IsEmpty())
                return Undefined();

            const mysqlpp::FieldNames *list = it->field_list().list;

            for (size_t i=0; i<it->size(); i++)
            {
                const Handle<Value> name = String::New((*list)[i].c_str());
                if (irow==0)
                    cols->Set(i, name);

                if ((*it)[i].is_null())
                {
                    row->Set(name, Undefined(), ReadOnly);
                    continue;
                }

                const string sql_type = (*it)[i].type().sql_name();

                const bool uns = sql_type.find("UNSIGNED")==string::npos;

                if (sql_type.find("BIGINT")!=string::npos)
                {
                    if (uns)
                    {
                        const uint64_t val = (uint64_t)(*it)[i];
                        if (val>UINT32_MAX)
                            row->Set(name, Number::New(val), ReadOnly);
                        else
                            row->Set(name, Integer::NewFromUnsigned(val), ReadOnly);
                    }
                    else
                    {
                        const int64_t val = (int64_t)(*it)[i];
                        if (val<INT32_MIN || val>INT32_MAX)
                            row->Set(name, Number::New(val), ReadOnly);
                        else
                            row->Set(name, Integer::NewFromUnsigned(val), ReadOnly);
                    }
                    continue;
                }

                // 32 bit
                if (sql_type.find("INT")!=string::npos)
                {
                    if (uns)
                        row->Set(name, Integer::NewFromUnsigned((uint32_t)(*it)[i]), ReadOnly);
                    else
                        row->Set(name, Integer::New((int32_t)(*it)[i]), ReadOnly);
                }

                if (sql_type.find("BOOL")!=string::npos )
                {
                    row->Set(name, Boolean::New((bool)(*it)[i]), ReadOnly);
                    continue;
                }

                if (sql_type.find("FLOAT")!=string::npos)
                {
                    ostringstream val;
                    val << setprecision(7) << (float)(*it)[i];
                    row->Set(name, Number::New(stod(val.str())), ReadOnly);
                    continue;

                }
                if (sql_type.find("DOUBLE")!=string::npos)
                {
                    row->Set(name, Number::New((double)(*it)[i]), ReadOnly);
                    continue;
                }

                if (sql_type.find("CHAR")!=string::npos ||
                    sql_type.find("TEXT")!=string::npos)
                {
                    row->Set(name, String::New((const char*)(*it)[i]), ReadOnly);
                    continue;
                }

                time_t date = 0;
                if (sql_type.find("TIMESTAMP")!=string::npos)
                    date = mysqlpp::Time((*it)[i]);

                if (sql_type.find("DATETIME")!=string::npos)
                    date = mysqlpp::DateTime((*it)[i]);

                if (sql_type.find(" DATE ")!=string::npos)
                    date = mysqlpp::Date((*it)[i]);

                if (date>0)
                {
                    // It is important to catch the exception thrown
                    // by Date::New in case of thread termination!
                    const Local<Value> val = Date::New(date*1000);
                    if (val.IsEmpty())
                        return Undefined();

                    row->Set(name, val, ReadOnly);
                }
            }

            ret->Set(irow++, row);
        }

        if (irow>0)
            ret->Set(String::New("cols"), cols, ReadOnly);

        return handle_scope.Close(ret);
    }
    catch (const exception &e)
    {
        return ThrowException(String::New(e.what()));
    }
#endif
}

Handle<Value> InterpreterV8::FuncDatabase(const Arguments &args)
{
    if (args.Length()!=1)
        return ThrowException(String::New("Number of arguments must be 1."));

    if (!args[0]->IsString())
        return ThrowException(String::New("Argument 1 not a string."));

#ifdef HAVE_SQL
    try
    {
        HandleScope handle_scope;

        Database *db = new Database(*String::Utf8Value(args[0]));
        fDatabases.push_back(db);

        Handle<ObjectTemplate> tem = ObjectTemplate::New();
        tem->Set(String::New("user"),     String::New(db->user.c_str()), ReadOnly);
        tem->Set(String::New("server"),   String::New(db->server.c_str()), ReadOnly);
        tem->Set(String::New("database"), String::New(db->db.c_str()), ReadOnly);
        tem->Set(String::New("port"),     db->port==0?Undefined():Integer::NewFromUnsigned(db->port), ReadOnly);
        tem->Set(String::New("query"),    FunctionTemplate::New(WrapDbQuery), ReadOnly);
        tem->Set(String::New("close"),    FunctionTemplate::New(WrapDbClose),   ReadOnly);
        tem->SetInternalFieldCount(1);

        Handle<Object> obj = tem->NewInstance();
        if (obj.IsEmpty())
            return Undefined();

        obj->SetInternalField(0, External::New(db));

        return handle_scope.Close(obj);
    }
    catch (const exception &e)
    {
        return ThrowException(String::New(e.what()));
    }
#endif
}

// ==========================================================================
//                                 Services
// ==========================================================================

Handle<Value> InterpreterV8::Convert(char type, const char* &ptr)
{
    // Dim values are always unsigned per (FACT++) definition
    switch (type)
    {
    case 'F':
        {
            // Remove the "imprecision" effect coming from casting a float to
            // a double and then showing it with double precision
            ostringstream val;
            val << setprecision(7) << *reinterpret_cast<const float*>(ptr);
            Handle<Value> v=Number::New(stod(val.str()));
            ptr+=4;
            return v;
        }
    case 'D':  { Handle<Value> v=Number::New(*reinterpret_cast<const double*>(ptr)); ptr+=8; return v; }
    case 'I':
    case 'L':  { Handle<Value> v=Integer::NewFromUnsigned(*reinterpret_cast<const uint32_t*>(ptr)); ptr += 4; return v; }
    case 'X':
        {
            const uint64_t val = *reinterpret_cast<const uint64_t*>(ptr);
            ptr += 8;
            if (val>UINT32_MAX)
                return Number::New(val);
            return Integer::NewFromUnsigned(val);
        }
    case 'S':  { Handle<Value> v=Integer::NewFromUnsigned(*reinterpret_cast<const uint16_t*>(ptr)); ptr += 2; return v; }
    case 'C':  { Handle<Value> v=Integer::NewFromUnsigned((uint16_t)*reinterpret_cast<const uint8_t*>(ptr));  ptr += 1; return v; }
    case ':':  { Handle<Value> v=String::New(ptr); return v; }
    }
    return Undefined();
}

Handle<Value> InterpreterV8::FuncClose(const Arguments &args)
{
    HandleScope handle_scope;

    //const void *ptr = Local<External>::Cast(args.Holder()->GetInternalField(0))->Value();

    const String::Utf8Value str(args.Holder()->Get(String::New("name")));

    const auto it = fReverseMap.find(*str);
    if (it!=fReverseMap.end())
    {
        it->second.Dispose();
        fReverseMap.erase(it);
    }

    args.Holder()->Set(String::New("isOpen"), Boolean::New(false), ReadOnly);

    return handle_scope.Close(Boolean::New(JsUnsubscribe(*str)));
}

Handle<Value> InterpreterV8::ConvertEvent(const EventImp *evt, uint64_t counter, const char *str)
{
    const vector<Description> vec = JsDescription(str);

    Handle<Array> ret = Array::New();
    if (ret.IsEmpty())
        return Undefined();

    const Local<Value> date = Date::New(evt->GetJavaDate());
    if (date.IsEmpty())
        return Undefined();

    ret->Set(String::New("name"),    String::New(str),             ReadOnly);
    ret->Set(String::New("format"),  String::New(evt->GetFormat().c_str()), ReadOnly);
    ret->Set(String::New("named"),   Boolean::New(vec.size()>0),    ReadOnly);
    ret->Set(String::New("qos"),     Integer::New(evt->GetQoS()),   ReadOnly);
    ret->Set(String::New("size"),    Integer::New(evt->GetSize()),  ReadOnly);
    ret->Set(String::New("counter"), Integer::New(counter),         ReadOnly);
    ret->Set(String::New("time"), date, ReadOnly);

    // If no event was received (usually a disconnection event in
    // the context of FACT++), no data is returned
    if (evt->IsEmpty())
        return ret;

    // If valid data was received, but the size was zero, then
    // null is returned as data
    if (evt->GetSize()==0 || evt->GetFormat().empty())
    {
        ret->Set(String::New("data"), Null(), ReadOnly);
        return ret;
    }

    typedef boost::char_separator<char> separator;
    const boost::tokenizer<separator> tokenizer(evt->GetFormat(), separator(";:"));

    const vector<string> tok(tokenizer.begin(), tokenizer.end());

    Handle<Array> obj = tok.size()>1 ? Array::New() : ret;
    if (obj.IsEmpty())
        return Undefined();

    const char *ptr = evt->GetText();
    const char *end = evt->GetText()+evt->GetSize();

    try
    {
        size_t pos = 1;
        for (auto it=tok.begin(); it!=tok.end() && ptr<end; it++, pos++)
        {
            char type = (*it)[0];
            it++;

            if (it==tok.end() && type=='C')
                type = ':';

            if (it==tok.end() && type!=':')
                return Exception::Error(String::New(("Format string invalid '"+evt->GetFormat()+"'").c_str()));

            string name = pos<vec.size() ? vec[pos].name : "";
            if (tok.size()==1)
                name = "data";

            const uint32_t cnt = it==tok.end() ? 1 : stoi(it->c_str());

            if (cnt==1)
            {
                const Handle<Value> v = Convert(type, ptr);
                if (tok.size()>1)
                    obj->Set(pos-1, v);
                if (!name.empty())
                    obj->Set(String::New(name.c_str()), v);
            }
            else
            {
                Handle<Array> a = Array::New(cnt);
                if (a.IsEmpty())
                    return Undefined();

                for (uint32_t i=0; i<cnt; i++)
                    a->Set(i, Convert(type, ptr));
                if (tok.size()>1)
                    obj->Set(pos-1, a);
                if (!name.empty())
                    obj->Set(String::New(name.c_str()), a);
            }

            if (it==tok.end())
                break;
        }

        if (tok.size()>1)
            ret->Set(String::New("data"), obj, ReadOnly);

        return ret;
    }
    catch (...)
    {
        return Exception::Error(String::New(("Format string conversion '"+evt->GetFormat()+"' failed.").c_str()));
    }
}
/*
Handle<Value> InterpreterV8::FuncGetData(const Arguments &args)
{
    HandleScope handle_scope;

    const String::Utf8Value str(args.Holder()->Get(String::New("name")));

    const pair<uint64_t, EventImp *> p = JsGetEvent(*str);

    const EventImp *evt = p.second;
    if (!evt)
        return Undefined();

    //if (counter==cnt)
    //    return info.Holder();//Holder()->Get(String::New("data"));

    Handle<Value> ret = ConvertEvent(evt, p.first, *str);
    return ret->IsNativeError() ? ThrowException(ret) : handle_scope.Close(ret);
}
*/
Handle<Value> InterpreterV8::FuncGetData(const Arguments &args)
{
    if (args.Length()>1)
        return ThrowException(String::New("Number of arguments must not be greatr than 1."));

    if (args.Length()==1 && !args[0]->IsInt32() && !args[0]->IsNull())
        return ThrowException(String::New("Argument 1 not an int32."));

    // Using a Javascript function has the advantage that it is fully
    // interruptable without the need of C++ code
    const bool    null    = args.Length()==1 && args[0]->IsNull();
    const int32_t timeout = args.Length()==1 ? args[0]->Int32Value() : 0;

    HandleScope handle_scope;

    const Handle<Script> sleep = Script::Compile(String::New("dim.sleep();"), String::New("internal"));
    if (sleep.IsEmpty())
        return Undefined();

    const Handle<String> data  = String::New("data");
    const Handle<String> named = String::New("named");

    const String::Utf8Value name(args.Holder()->Get(String::New("name")));

    TryCatch exception;

    Time t;
    while (!exception.HasCaught())
    {
        const pair<uint64_t, EventImp *> p = JsGetEvent(*name);

        const EventImp *evt = p.second;
        if (evt)
        {
            const Handle<Value> val = ConvertEvent(evt, p.first, *name);
            if (val->IsNativeError())
                return ThrowException(val);

            // Protect against the return of an exception
            if (!val.IsEmpty() && val->IsObject())
            {
                const Handle<Object> obj = val->ToObject();
                if (obj->Has(data) && obj->Get(named)->ToBoolean()->Value())
                    return handle_scope.Close(val);
            }
        }

        if (args.Length()==0)
            break;

        if (!null && Time()-t>=boost::posix_time::milliseconds(abs(timeout)))
            break;

        // We cannot sleep directly because we have to give control back to
        // JavaScript ever now and then. This also allows us to catch
        // exceptions, either from the preemption or ConvertEvent
        sleep->Run();
    }

    if (exception.HasCaught())
        return exception.ReThrow();

    if (timeout>=0)
        return Undefined();

    const string str = "Waiting for a valid event of "+string(*name)+" timed out.";
    return ThrowException(String::New(str.c_str()));
}


// This is a callback from the RemoteControl piping event handling
// to the java script ---> in test phase!
void InterpreterV8::JsHandleEvent(const EventImp &evt, uint64_t cnt, const string &service)
{
    const Locker locker;

    if (fThreadId<0)
        return;

    const auto it = fReverseMap.find(service);
    if (it==fReverseMap.end())
        return;

    const HandleScope handle_scope;

    fGlobalContext->Enter();

    Handle<Object> obj = it->second;
    if (obj.IsEmpty())
        return;

    const Handle<String> onchange = String::New("onchange");
    if (!obj->Has(onchange))
        return;

    const Handle<Value> val = obj->Get(onchange);
    if (!val->IsFunction())
        return;

    // -------------------------------------------------------------------
    TryCatch exception;

    const int id = V8::GetCurrentThreadId();
    fThreadIds.insert(id);

    Handle<Value> ret = ConvertEvent(&evt, cnt, service.c_str());
    if (ret->IsArray())
    {
        Handle<Array> data = Handle<Array>::Cast(ret);
        Handle<Value> args[] = { data };

        Handle<Function>::Cast(val)->Call(obj, 1, args);
    }

    fThreadIds.erase(id);

    if (exception.HasCaught())
        ReportException(&exception);

    if (ret->IsNativeError())
        JsException(service+".onchange callback - "+*String::Utf8Value(ret));

    if (ret->IsUndefined() || ret->IsNativeError() || exception.HasCaught())
        Terminate();
}

Handle<Value> InterpreterV8::OnChangeSet(Local<String> prop, Local< Value > value, const AccessorInfo &)
{
    // Returns the value if the setter intercepts the request. Otherwise, returns an empty handle.
    const string server = *String::Utf8Value(prop);
    auto it = fStateCallbacks.find(server);

    if (it!=fStateCallbacks.end())
    {
        it->second.Dispose();
        fStateCallbacks.erase(it);
    }

    if (value->IsFunction())
        fStateCallbacks[server] = Persistent<Value>::New(value);

    return Handle<Value>();
}


void InterpreterV8::JsHandleState(const std::string &server, const State &state)
{
    const Locker locker;

    if (fThreadId<0)
        return;

    auto it = fStateCallbacks.find(server);
    if (it==fStateCallbacks.end())
    {
        it = fStateCallbacks.find("*");
        if (it==fStateCallbacks.end())
            return;
    }

    if (it->second.IsEmpty() || !it->second->IsFunction())
        return;

    const HandleScope handle_scope;

    fGlobalContext->Enter();

    // -------------------------------------------------------------------

    Handle<ObjectTemplate> obj = ObjectTemplate::New();
    obj->Set(String::New("index"),   state.index<=-256?Undefined():Integer::New(state.index),          ReadOnly);
    obj->Set(String::New("name"),    state.index<=-256?Undefined():String::New(state.name.c_str()),    ReadOnly);
    obj->Set(String::New("comment"), state.index<=-256?Undefined():String::New(state.comment.c_str()), ReadOnly);
    obj->Set(String::New("server"),  String::New(server.c_str()), ReadOnly);

    const Local<Value> date = Date::New(state.time.JavaDate());
    if (state.index>-256 && !date.IsEmpty())
        obj->Set(String::New("time"), date);

    // -------------------------------------------------------------------

    TryCatch exception;

    const int id = V8::GetCurrentThreadId();
    fThreadIds.insert(id);

    Handle<Value> args[] = { obj->NewInstance() };
    Handle<Function> fun = Handle<Function>::Cast(it->second);
    fun->Call(fun, 1, args);

    fThreadIds.erase(id);

    if (!exception.HasCaught())
        return;

    ReportException(&exception);
    Terminate();
}

/*
void Cleanup( Persistent<Value> object, void *parameter )
{
    cout << "======================> RemoveMyObj()" << endl;
}*/

Handle<Value> InterpreterV8::FuncSubscribe(const Arguments &args)
{
    if (args.Length()!=1)
        return ThrowException(String::New("Number of arguments must be exactly 1."));

    if (!args[0]->IsString())
        return ThrowException(String::New("Argument 1 must be a string."));

    //if (!args.IsConstructCall())
    //    return ThrowException(String::New("Must be used as constructor."));

    const String::Utf8Value str(args[0]);

    const auto it = fReverseMap.find(*str);
    if (it!=fReverseMap.end())
        return it->second;

    void *ptr = JsSubscribe(*str);
    if (ptr==0)
        return ThrowException(String::New(("Subscription to '"+string(*str)+"' already exists.").c_str()));

    HandleScope handle_scope;

    Handle<ObjectTemplate> tem = ObjectTemplate::New();
    tem->Set(String::New("get"),    FunctionTemplate::New(WrapGetData),  ReadOnly);
    tem->Set(String::New("close"),  FunctionTemplate::New(WrapClose),    ReadOnly);
    tem->Set(String::New("name"),   String::New(*str), ReadOnly);
    tem->Set(String::New("isOpen"), Boolean::New(true));
    tem->SetInternalFieldCount(1);
    //tem->Set(String::New("toString"), String::New(("[object Dim "+string(*str)+"]").c_str()), ReadOnly);

    Handle<Object> obj = tem->NewInstance();
    if (obj.IsEmpty())
        return Undefined();

    obj->SetInternalField(0, External::New(ptr));

    fReverseMap[*str] = Persistent<Object>::New(obj);

    return handle_scope.Close(obj);

    // Persistent<Object> p = Persistent<Object>::New(obj->NewInstance());
    // obj.MakeWeak((void*)1, Cleanup);
    // return obj;
}

// ==========================================================================
//                            Astrometry
// ==========================================================================
#ifdef HAVE_NOVA

double InterpreterV8::GetDataMember(const Arguments &args, const char *name)
{
    return args.This()->Get(String::New(name))->NumberValue();
}

Handle<Value> InterpreterV8::LocalToString(const Arguments &/*args*/)
{
    return String::New("[object Local]");
    /*
    HandleScope handle_scope;

    const Handle<Object> This = args.This();

    Handle<String> zd = This->Get(String::New("zd"))->ToString();
    Handle<String> az = This->Get(String::New("az"))->ToString();

    return String::New("TEST");
    */
}

Handle<Value> InterpreterV8::SkyToString(const Arguments &/*args*/)
{
    return String::New("[object Sky]");
}

Handle<Value> InterpreterV8::MoonToString(const Arguments &/*args*/)
{
    return String::New("[object Moon]");
}

Handle<Value> InterpreterV8::ConstructLocal(double zd, double az, Handle<Value> time)
{
    Handle<ObjectTemplate> loc = ObjectTemplate::New();

    loc->Set(String::New("zd"),       Number::New(zd), ReadOnly);
    loc->Set(String::New("az"),       Number::New(az), ReadOnly);
    loc->Set(String::New("toSky"),    FunctionTemplate::New(LocalToSky), ReadOnly);
    loc->Set(String::New("toString"), FunctionTemplate::New(LocalToString), ReadOnly);
    if (!time.IsEmpty())
        loc->Set(String::New("time"), time);

    return loc->NewInstance();
}

Handle<Value> InterpreterV8::ConstructSky(double ra, double dec, Handle<Value> time, bool ismoon)
{
    Handle<ObjectTemplate> sky = ObjectTemplate::New();

    sky->Set(String::New("ra"),       Number::New(ra),  ReadOnly);
    sky->Set(String::New("dec"),      Number::New(dec), ReadOnly);
    sky->Set(String::New("toLocal"),  FunctionTemplate::New(ismoon?MoonToLocal :SkyToLocal),  ReadOnly);
    sky->Set(String::New("toString"), FunctionTemplate::New(ismoon?MoonToString:SkyToString), ReadOnly);
    if (!time.IsEmpty())
        sky->Set(String::New("time"), time);

    return sky->NewInstance();
}

Handle<Value> InterpreterV8::LocalDist(const Arguments &args)
{
    if (args.Length()!=2)
        return ThrowException(String::New("dist must not be called with two arguments."));

    if (!args[0]->IsObject() || !args[1]->IsObject())
        return ThrowException(String::New("at least one argument not an object."));

    HandleScope handle_scope;

    Handle<Object> obj[2] =
    {
        Handle<Object>::Cast(args[0]),
        Handle<Object>::Cast(args[1])
    };

    const Handle<String> s_zd = String::New("zd");
    const Handle<String> s_az = String::New("az");

    const double zd0 = obj[0]->Get(s_zd)->NumberValue() * M_PI/180;
    const double az0 = obj[0]->Get(s_az)->NumberValue() * M_PI/180;
    const double zd1 = obj[1]->Get(s_zd)->NumberValue() * M_PI/180;
    const double az1 = obj[1]->Get(s_az)->NumberValue() * M_PI/180;

    if (!finite(zd0) || !finite(zd1) || !finite(az0) || !finite(az1))
        return ThrowException(String::New("some values not valid or not finite."));

    /*
    const double x0 = sin(zd0) * cos(az0);   // az0 -= az0
    const double y0 = sin(zd0) * sin(az0);   // az0 -= az0
    const double z0 = cos(zd0);

    const double x1 = sin(zd1) * cos(az1);   // az1 -= az0
    const double y1 = sin(zd1) * sin(az1);   // az1 -= az0
    const double z1 = cos(zd1);

    const double res = acos(x0*x1 + y0*y1 + z0*z1) * 180/M_PI;
    */

    // cos(az1-az0) = cos(az1)*cos(az0) + sin(az1)*sin(az0)

    const double x = sin(zd0) * sin(zd1) * cos(az1-az0);
    const double y = cos(zd0) * cos(zd1);

    const double res = acos(x + y) * 180/M_PI;

    return handle_scope.Close(Number::New(res));
}

Handle<Value> InterpreterV8::MoonDisk(const Arguments &args)
{
    if (args.Length()>1)
        return ThrowException(String::New("disk must not be called with more than one argument."));

    const uint64_t v = uint64_t(args[0]->NumberValue());
    const Time utc = args.Length()==0 ? Time() : Time(v/1000, v%1000);

    return Number::New(ln_get_lunar_disk(utc.JD()));
}

Handle<Value> InterpreterV8::LocalToSky(const Arguments &args)
{
    if (args.Length()>1)
        return ThrowException(String::New("toSky must not be called with more than one argument."));

    ln_hrz_posn hrz;
    hrz.alt = 90-GetDataMember(args, "zd");
    hrz.az  =    GetDataMember(args, "az");

    if (!finite(hrz.alt) || !finite(hrz.az))
        return ThrowException(String::New("zd and az must be finite."));

    HandleScope handle_scope;

    const Local<Value> date =
        args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
    if (date.IsEmpty())
        return Undefined();

    const uint64_t v = uint64_t(date->NumberValue());
    const Time utc(v/1000, v%1000);

    ln_lnlat_posn obs;
    obs.lng = -(17.+53./60+26.525/3600);
    obs.lat =   28.+45./60+42.462/3600;

    ln_equ_posn equ;
    ln_get_equ_from_hrz(&hrz, &obs, utc.JD(), &equ);

    return handle_scope.Close(ConstructSky(equ.ra/15, equ.dec, date));
}

Handle<Value> InterpreterV8::SkyToLocal(const Arguments &args)
{
    if (args.Length()>1)
        return ThrowException(String::New("toLocal must not be called with more than one argument."));

    ln_equ_posn equ;
    equ.ra  = GetDataMember(args, "ra")*15;
    equ.dec = GetDataMember(args, "dec");

    if (!finite(equ.ra) || !finite(equ.dec))
        return ThrowException(String::New("Ra and dec must be finite."));

    HandleScope handle_scope;

    const Local<Value> date =
        args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
    if (date.IsEmpty())
        return Undefined();

    const uint64_t v = uint64_t(date->NumberValue());
    const Time utc(v/1000, v%1000);

    ln_lnlat_posn obs;
    obs.lng = -(17.+53./60+26.525/3600);
    obs.lat =   28.+45./60+42.462/3600;

    ln_hrz_posn hrz;
    ln_get_hrz_from_equ(&equ, &obs, utc.JD(), &hrz);

    return handle_scope.Close(ConstructLocal(90-hrz.alt, hrz.az, date));
}

Handle<Value> InterpreterV8::MoonToLocal(const Arguments &args)
{
    if (args.Length()>0)
        return ThrowException(String::New("toLocal must not be called with arguments."));

    ln_equ_posn equ;
    equ.ra  = GetDataMember(args, "ra")*15;
    equ.dec = GetDataMember(args, "dec");

    if (!finite(equ.ra) || !finite(equ.dec))
        return ThrowException(String::New("ra and dec must be finite."));

    HandleScope handle_scope;

    const Local<Value> date =
        args.Length()==0 ? Date::New(Time().JavaDate()) : args.This()->Get(String::New("time"));
    if (date.IsEmpty())
        return Undefined();

    const uint64_t v = uint64_t(date->NumberValue());
    const Time utc(v/1000, v%1000);

    ln_lnlat_posn obs;
    obs.lng = -(17.+53./60+26.525/3600);
    obs.lat =   28.+45./60+42.462/3600;

    ln_hrz_posn hrz;
    ln_get_hrz_from_equ(&equ, &obs, utc.JD(), &hrz);

    return handle_scope.Close(ConstructLocal(90-hrz.alt, hrz.az, date));
}

Handle<Value> InterpreterV8::ConstructorMoon(const Arguments &args)
{
    if (args.Length()>1)
        return ThrowException(String::New("Moon constructor must not be called with more than one argument."));

    HandleScope handle_scope;

    const Local<Value> date =
        args.Length()==0 ? Date::New(Time().JavaDate()) : args[0];
    if (date.IsEmpty())
        return Undefined();

    const uint64_t v = uint64_t(date->NumberValue());
    const Time utc(v/1000, v%1000);

    ln_equ_posn equ;
    ln_get_lunar_equ_coords_prec(utc.JD(), &equ, 0.01);

    return handle_scope.Close(ConstructSky(equ.ra/15, equ.dec, date, true));
}

Handle<Value> InterpreterV8::ConstructorSky(const Arguments &args)
{
    if (args.Length()!=2)
        return ThrowException(String::New("Sky constructor takes two arguments."));

    const double ra  = args[0]->NumberValue();
    const double dec = args[1]->NumberValue();

    if (!finite(ra) || !finite(dec))
        return ThrowException(String::New("Both arguments to Sky must be valid numbers."));

    return ConstructSky(ra, dec);
}

Handle<Value> InterpreterV8::ConstructorLocal(const Arguments &args)
{
    if (args.Length()!=2)
        return ThrowException(String::New("Local constructor takes two arguments."));

    const double zd = args[0]->NumberValue();
    const double az = args[1]->NumberValue();

    if (!finite(zd) || !finite(az))
        return ThrowException(String::New("Both arguments to Local must be valid numbers."));

    return ConstructLocal(zd, az);
}
#endif

// ==========================================================================
//                            Process control
// ==========================================================================

bool InterpreterV8::ReportException(TryCatch* try_catch)
{
    if (!try_catch->CanContinue())
        return false;

    const HandleScope handle_scope;

    const String::Utf8Value exception(try_catch->Exception());

    if (*exception && string(*exception)=="exit")
        return true;
    if (*exception && string(*exception)=="null")
        return false;

    const Handle<Message> message = try_catch->Message();
    if (message.IsEmpty())
        return false;

    ostringstream out;

    if (!message->GetScriptResourceName()->IsUndefined())
    {
        // Print (filename):(line number): (message).
        const String::Utf8Value filename(message->GetScriptResourceName());

        if (*filename)
            out << *filename << ": ";
        out << "l." << message->GetLineNumber();
        if (*exception)
            out << ": ";
    }

    // -------------- SKIP if 'internal' and 'Error' ---------------
    if (*exception)
        out << *exception;

    JsException(out.str());

    // Print line of source code.
    const String::Utf8Value sourceline(message->GetSourceLine());
    if (*sourceline)
        JsException(*sourceline);
    // -------------- SKIP if 'internal' and 'Error: ' ---------------

    // Print wavy underline (GetUnderline is deprecated).
    const int start = message->GetStartColumn();
    const int end   = message->GetEndColumn();

    out.str("");
    if (start>0)
        out << setfill(' ') << setw(start) << ' ';
    out << setfill('^') << setw(end-start) << '^';

    JsException(out.str());

    const String::Utf8Value stack_trace(try_catch->StackTrace());
    if (stack_trace.length()<=0)
        return false;

    if (!*stack_trace)
        return false;

    const string trace(*stack_trace);

    typedef boost::char_separator<char> separator;
    const boost::tokenizer<separator> tokenizer(trace, separator("\n"));

    // maybe skip: "    at internal:"

    auto it = tokenizer.begin();
    JsException("");
    while (it!=tokenizer.end())
        JsException(*it++);

    return false;
}

Handle<Value> InterpreterV8::ExecuteInternal(const string &code)
{
    TryCatch exception;
    const Handle<Value> result = ExecuteCode(code);
    return exception.HasCaught() ? exception.ReThrow() : result;
}

Handle<Value> InterpreterV8::ExecuteCode(const string &code, const string &file, bool main)
{
    HandleScope handle_scope;

    const Handle<String> source = String::New(code.c_str(), code.size());
    const Handle<String> origin = String::New(file.c_str());
    if (source.IsEmpty())
        return Handle<Value>();

    const Handle<Script> script = Script::Compile(source, origin);
    if (script.IsEmpty())
        return Handle<Value>();

    if (main)
        JsSetState(3);

    const Handle<Value> result = script->Run();
    if (result.IsEmpty())
        return result;

    // If all went well and the result wasn't undefined then print
    // the returned value.
    if (!result->IsUndefined())
        JsResult(*String::Utf8Value(result));

    return handle_scope.Close(result);
}

bool InterpreterV8::ExecuteFile(const string &name, bool main)
{
    ifstream fin(name.c_str());
    if (!fin)
    {
        JsException("Error - Could not open file '"+name+"'");
        return false;
    }

    string buffer;
    if (!getline(fin, buffer, '\0'))
        return true;

    if (fin.fail())
    {
        JsException("Error - reading file.");
        return false;
    }

    return !ExecuteCode(buffer, name, main).IsEmpty();
}

// ==========================================================================
//                                  CORE
// ==========================================================================

void InterpreterV8::AddFormatToGlobal() const
{
    const string code =
        "dim.format = function(str, arr)"
        "{"
            "var i = -1;"
            "function callback(exp, p0, p1, p2, p3, p4/*, pos, str*/)"
            "{"
                "if (exp=='%%')"
                    "return '%';"
                ""
                "if (arr[++i]===undefined)"
                    "return undefined;"
                ""
                "var exp  = p2 ? parseInt(p2.substr(1)) : undefined;"
                "var base = p3 ? parseInt(p3.substr(1)) : undefined;"
                ""
                "var val;"
                "switch (p4)"
                "{"
                "case 's': val = arr[i]; break;"
                "case 'c': val = arr[i][0]; break;"
                "case 'f': val = parseFloat(arr[i]).toFixed(exp); break;"
                "case 'p': val = parseFloat(arr[i]).toPrecision(exp); break;"
                "case 'e': val = parseFloat(arr[i]).toExponential(exp); break;"
                "case 'x': val = parseInt(arr[i]).toString(base?base:16); break;"
                "case 'd': val = parseFloat(parseInt(arr[i], base?base:10).toPrecision(exp)).toFixed(0); break;"
                //"default:\n"
                //"    throw new SyntaxError('Conversion specifier '+p4+' unknown.');\n"
                "}"
                ""
                "val = typeof(val)=='object' ? JSON.stringify(val) : val.toString(base);"
                ""
                "var sz = parseInt(p1); /* padding size */"
                "var ch = p1 && p1[0]=='0' ? '0' : ' '; /* isnull? */"
                "while (val.length<sz)"
                    "val = p0 !== undefined ? val+ch : ch+val; /* isminus? */"
                ""
                "return val;"
            "}"
            ""
            "var regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd])/g;"
            "return str.replace(regex, callback);"
        "}"
        "\n"
        "String.prototype.$ = function()"
        "{"
            "return dim.format(this, Array.prototype.slice.call(arguments));"
        "}"/*
        "\n"
        "var format = function()"
        "{"
            "return dim.format(arguments[0], Array.prototype.slice.call(arguments,1));"
        "}"*/;

    Script::New(String::New(code.c_str()), String::New("internal"))->Run();
}

bool InterpreterV8::JsRun(const string &filename, const map<string, string> &map)
{
    const Locker locker;
    fThreadId = V8::GetCurrentThreadId();

    JsPrint(string("JavaScript Engine V8 ")+V8::GetVersion());

    JsLoad(filename);

    const HandleScope handle_scope;

    // Create a template for the global object.
    Handle<ObjectTemplate> dim = ObjectTemplate::New();
    dim->Set(String::New("print"),     FunctionTemplate::New(WrapPrint),     ReadOnly);
    dim->Set(String::New("alarm"),     FunctionTemplate::New(WrapAlarm),     ReadOnly);
    dim->Set(String::New("out"),       FunctionTemplate::New(WrapOut),       ReadOnly);
    dim->Set(String::New("wait"),      FunctionTemplate::New(WrapWait),      ReadOnly);
    dim->Set(String::New("send"),      FunctionTemplate::New(WrapSend),      ReadOnly);
    dim->Set(String::New("state"),     FunctionTemplate::New(WrapState),     ReadOnly);
    dim->Set(String::New("newState"),  FunctionTemplate::New(WrapNewState),  ReadOnly);
    dim->Set(String::New("setState"),  FunctionTemplate::New(WrapSetState),  ReadOnly);
    dim->Set(String::New("sleep"),     FunctionTemplate::New(WrapSleep),     ReadOnly);
    dim->Set(String::New("timeout"),   FunctionTemplate::New(WrapTimeout),   ReadOnly);
    dim->Set(String::New("subscribe"), FunctionTemplate::New(WrapSubscribe), ReadOnly);
    dim->Set(String::New("database"),  FunctionTemplate::New(WrapDatabase),  ReadOnly);

    Handle<ObjectTemplate> onchange = ObjectTemplate::New();
    onchange->SetNamedPropertyHandler(OnChangeGet, WrapOnChangeSet);
    dim->Set(v8::String::New("onchange"), onchange);

    Handle<ObjectTemplate> global = ObjectTemplate::New();
    global->Set(String::New("dim"), dim, ReadOnly);
    global->Set(String::New("include"), FunctionTemplate::New(WrapInclude),                ReadOnly);
    global->Set(String::New("exit"),    FunctionTemplate::New(WrapExit),                   ReadOnly);
    global->Set(String::New("version"), FunctionTemplate::New(InterpreterV8::FuncVersion), ReadOnly);

#ifdef HAVE_NOVA
    Handle<FunctionTemplate> sky = FunctionTemplate::New(ConstructorSky);
    global->Set(String::New("Sky"), sky, ReadOnly);

    Handle<FunctionTemplate> loc = FunctionTemplate::New(ConstructorLocal);
    loc->Set(String::New("dist"), FunctionTemplate::New(LocalDist), ReadOnly);
    global->Set(String::New("Local"), loc, ReadOnly);

    Handle<FunctionTemplate> moon = FunctionTemplate::New(ConstructorMoon);
    moon->Set(String::New("disk"), FunctionTemplate::New(MoonDisk), ReadOnly);
    global->Set(String::New("Moon"), moon, ReadOnly);
#endif

    // Persistent
    fGlobalContext = Context::New(NULL, global);
    if (fGlobalContext.IsEmpty())
    {
        //printf("Error creating context\n");
        return false;
    }

    Context::Scope scope(fGlobalContext);

    Handle<Array> args = Array::New(map.size());
    for (auto it=map.begin(); it!=map.end(); it++)
        args->Set(String::New(it->first.c_str()), String::New(it->second.c_str()));
    fGlobalContext->Global()->Set(String::New("$"),   args, ReadOnly);
    fGlobalContext->Global()->Set(String::New("arg"), args, ReadOnly);

    AddFormatToGlobal();

    JsStart(filename);

    //context->Enter();

    TryCatch exception;

    Locker::StartPreemption(10);
    bool rc = ExecuteFile(filename, true);
    Locker::StopPreemption();

    Terminate();

    if (exception.HasCaught())
        rc = ReportException(&exception);

    // -----
    // This is how an exit handler could look like, but there is no way to interrupt it
    // -----
    // Handle<Object> obj = Handle<Object>::Cast(context->Global()->Get(String::New("dim")));
    // if (!obj.IsEmpty())
    // {
    //     Handle<Value> onexit = obj->Get(String::New("onexit"));
    //     if (!onexit->IsUndefined())
    //         Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
    //     // Handle<Object> result = Handle<Function>::Cast(onexit)->NewInstance(0, NULL); // argc, argv
    // }

    //context->Exit();

    // Thre threads are started already and wait to get the lock
    // So we have to unlock (manual preemtion) so they they get
    // the signal to terminate. After they are all successfully
    // terminated, just to be sure... we lock again
    {
        const Unlocker unlock;

        for (auto it=fTimeout.begin(); it!=fTimeout.end(); it++)
            it->join();
        fTimeout.clear();
    }

    // Now we can dispose all persistent handles from state callbacks
    for (auto it=fStateCallbacks.begin(); it!=fStateCallbacks.end(); it++)
        it->second.Dispose();
    fStateCallbacks.clear();

    // Now we can dispose all persistent handles from reverse maps
    for (auto it=fReverseMap.begin(); it!=fReverseMap.end(); it++)
        it->second.Dispose();
    fReverseMap.clear();

#ifdef HAVE_SQL
    // ...and close all database  handles
    for (auto it=fDatabases.begin(); it!=fDatabases.end(); it++)
        delete *it;
    fDatabases.clear();
#endif

    JsEnd(filename);

    return rc;
}

void InterpreterV8::JsStop()
{
    Locker locker;
    This->Terminate();
}

#endif

InterpreterV8 *InterpreterV8::This = 0;
