refactoring + fixed memory leak