fixed some leaks and edge cases