Refactored to remove unnecessary loops