Some refactoring to remove duplicate code and other clean-ups