almost working counting

and some refactoring.