Refactored a bit to avoid code repetition