Fix bunch of memory leaks and deadlocks found by valgrind