making some changes less hacky

extracting repeated function blocks to their own functions.