Fixed some bugs and memory leaks