fixed conunter; some code refactoring