Changed counting to use better algorithm