Improve counting logic