Lots of fixes, most of them from Valgrind