Ran valgrind + thread sanitiser, fixed a number of races.