in reply to warning "Out of memory!"

At the risk of being repetitive, it's always more difficult to give advice on how to improve the script when you you haven't explained what it's supposed to do.

What is your input, your expected output, and your actual output? And have a look at this How do I post a question effectively?