fix a race condition and other improvements