Minor bug fixes and refactoring.