refactoring, fixed memory leaks