Made it more thread safe and simplified