Fix memory leaks and reduce the number of differences vs master.