[fixes #3] refactor to remove race condition