Added a var count function and moved for loop inside