Refactor some functions while adding tests