Fixed memory leaks and issues