refactor of counting code