Fixes a few logic bugs, including a race condition.