Some refactoring and bug fixes