Memory management and other fixes from James H.