Fix memory leaks, remove unused code