added bounds-checking to the code