Added tests, fixed some race conditions.