corrected some race conditions discovered by testing