Fixed most of the memory leaks and some refactoring