Simpler code.

The code for this was overly complex and would suffer from race conditions when dealing with multiple threads calling it. I'm not 100% sure I've solved all the thread race issues but this version is a lot less complex.

I submit this code merely as a suggestion that sometimes problems are more complex than you might initially think but can also have simpler solutions than you might initially code.

- Regards