Cleaned up and debugged race conditions