Fixed lots of bugs in multi-threaded version, which now works as expected.