Doing it all in one function was messy and hard to follow. I've broken it into several smaller functions, so now I know what is going on.