replaced repeating blocks of code with a function