code cleanup and memory leak fixed