Further improvements and refactoring.