Bug fixes and refactoring