More duplicate code moved into a function