This whole function is kinda hard to follow - it'd be much nicer if it wasn't mutating objects so much. Let's chat about it at a whiteboard.