Multiple patches to make valgrind happy and one to the logic