Check array length before indexing. Fixes #603

This fixes #603 the problem was not checking the array length first.