Refactor some more - move out chunks of code to their own functions