Some refactoring and bug fixing