Improved count function