Refactored to be more efficient and logical