fixed a bunch of logical errors in code.

fixed some index issues in for loops