Refactored a bit to avoid code duplication