Various minor bug fixes and refactoring.