fixed memory leaks and bugs