move the counting out of loop