some refactoring
and fix memory leak