Refactored to use generator