Refactored a bunch of stuff into functions and abstracted it out.