Some refactoring and style fixes