fixed index out of bounds errors

and misc. refactoring.