Refactoring and bug fixes