Small refactoring and bug fixing