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.