Memory leaks and some bugs fixed