Multiple performance improvements, refactoring