Refactored and fixed edge case