fixed a race condition and a couple of segfaults