Function-ified it
it got messier :(