some cleanup and fixing of memory issue