array out of bounds fixed, refactored functions