Bug fixes, and code refactoring