some refactoring and bug fixing