Fixed race condition. Added documentation