Fix several bugs causing unit tests to fail occasionally. Closes #232.