There is some code duplication here compared to the previous function.