Fix a memory overuse problem and sort some semi-duplicate code into another function to keep scrutinizer happy.