refactoring so we're less prone to race conditions