Misc fixes and refactoring