This method seems to be pretty complicated, could do with a few docstrings to describe why it does things in a certain way.