fix memory leaks.  Includes fix spoted by @pmed