fix memory leak issues
some refactor of memory managment