
struct IPCServer : wxServer
{
    wxConnectionBase *OnAcceptConnection(const wxString& topic)
    {
        sys->frame->RequestUserAttention();
        sys->Open(topic);
        return new wxConnection();
    }
};

struct MyApp : wxApp
{
    MyFrame *frame;
    wxSingleInstanceChecker *checker;
    IPCServer *serv;

    MyApp() : checker(NULL), frame(NULL), serv(NULL) {}

    bool OnInit()
    {
        wxDisableAsserts();

        ProtectStackOverflow();

        #if wxUSE_UNICODE==0
            #error "must use unicode version of wx libs to ensure data integrity of .rs files"
        #endif
        ASSERT(wxUSE_UNICODE);

        const wxString name = wxString::Format(L"Restructor-%s", wxGetUserId().c_str());
        checker = new wxSingleInstanceChecker(name);
        if(checker->IsAnotherRunning())
        {
            if(argc==2)
            {
                wxClient client;
                client.MakeConnection(L"localhost", L"4242", argv[1]);  // fire and forget
            }
            return false;
        }

        sys = new System();
        frame = new MyFrame(argv[0]);
        SetTopWindow(frame);
        sys->Init(argc, argv);

        serv = new IPCServer();
        serv->Create(L"4242");

        return true;
    }

    int OnExit()
    {
        DELETEP(serv);
        DELETEP(sys);
        DELETEP(checker);
        return 0;
    }

    #ifdef __WXMAC__
    void MacOpenFile(const wxString &fn)
    {
        if(sys) sys->Open(fn);
    }
    #endif

    DECLARE_EVENT_TABLE()

    void ProtectStackOverflow()
    {
        #ifdef _DEBUG
            char _dummy;
            char *curstack = &_dummy;
            curstack = (char *)(((size_t)curstack)&~0xFFFF);
            curstack += 0x20000;
            DWORD old;
            ASSERT(VirtualProtect(curstack, 0x1000, PAGE_READONLY, &old));
        #endif
    }
};
