Some refactoring and code clean-up