Minor bug fixes and code refactoring