fix some memory leaks and bugs.