Fix #9 - found the buffer overrun, and also cleaned up several other
memory leaks reported by valgrind.