When posting code, please use highlight tags to preserve formatting. Also, you haven't described what exactly is going on. What do you mean by "it starts to go wrong"? What do you expect to happen? What happens instead? Have you stepped through this with a debugger, or at least with a piece of paper and a pencil? When does the code deviate from your expectations?