Changed duplicate code to be factored into single function.