~ refactor. vectorize two helper functions.