Fixed some possible memory leaks and code style