deadlock and segfault fixes and many more. also added a tests.cpp