Small change in order of events to fix a possible race condition.  (UNTESTED)