Some refactoring and polish