Fix memory leaks and bugs