Various race conditions and other fixes