Fix the memory corruption

Spent some quality time with valgrind and managed to solve the memory corruption, reported as Issue #2.  Fixed a couple of other valgrind issues.