Fix race condition caused by improper state change.
Proper fix for the race condition from the previous commit.
yet another (more clear) solution to the race condition.
Final fixes before submitting the patch