Some performance improvements and refactoring