Fixing memory leaks and some logic.