Minor refactoring and bug fixes.