cleaned up code a bit (double use of variable i)