refactored code a bit to avoid memory issues