Added various refinements and fixes for little bugs caught by valgrind.