Fixed race condition, and upgraded error handling