Fixed an out of bounds error and some refactoring.