fixed memory leaks and errors