Refactorize some code to make it simpler