Small refactoring and bug fixes