Fix a lot of duplicate code