Some refactoring and minor changes