Slightly simpler logic, pointed out in code review.