Refactor count function