combining repeated code into function