Even more optimization and refactoring