Added checks to avoid IndexOutOfBoundsExceptions