Fix and rewrite the child-sorting code.