Moved if-statement to top of loop to handle the first iteration in the loop properly.