Some refactoring and code reorganization.