refactored and fixed a memory leak