Initial clean up testing and improvements to prevent memory leaks. Not done yet.