refactoring and more leak fixes