memory leaks and other fixes