Refactored a little bit to remove duplicate code