It strikes me that this function is basically the same as the other one. Could you do some refactoring to avoid repeating this very large function?