Move repeated code to function