Rearrange code to remove duplication