Here too. I think the functional approach would make this whole function a lot shorter and clearer.