Replaced repetitive code with function.