Small bug fixes and refactoring.