some code deduplication and cleanup