Fixes for Visual C++ compatibility
A lot of refactoring in preparation for further development, not sure it works now, but at least compiles :)