Bug fixes, code refactoring