fix array out of bounds exception in some edge cases