Made the code (kind of) cleaner by splitting it into functions.