The function has a lot of repeated code. Need to refactor functionality out into smaller functions. (And quite possibly rename the function too ;) )