moved some repeated code to a function