Bunch of stability fixes

Mostly, memory leaks and violations caught by valgrind.