Major refactoring, minor fixes and optimizations