in reply to out of memory!

I agree with tall_man. You have posted a very long piece of code and asked for us to debug it for you. It would be better if you could show some effort and begin debugging it yourself. A simple way you could do this is to start taking out unnecessary parts of the code, until you have shrunken it down to just a few lines of code that produce the same problem you are describing. Then you could paste those few lines of code.