Refactored a bit and added a little more thread safety