fixed race conditions with callbacks, refactored as well