given that the function has essentially two different implementations buried in it, shouldn't this be split into two overloads?

Otherwise, lgtm!