Refactored code to handle memory issues