Cut down on duplicate code

Use a recursive function