Some refactoring and deduplication