Refactor duplication of code and make it a bit more readable