made the code faster by going through the data once