Refactored to try and reduce possible race conditions