memory leak fix and bug fixes