Would you mind extracting this into a function that describes a bit more of what is going on? If you don't know what that is, it's no big deal.

These functions got a little bit out of control and could use a bit of love to make them tinier :)