Miscellaneous bug fixes and refactoring