Some improvements and refactoring.