Miscellaneous fixes and refactoring