Refactor some code, remove duplicate code