Moved some code to functions.

Noticed a lot of repeated code. Figured it's easier to maintain if I moved some of them to functions.