Add bounds check to index access.

Received a number of exceptions from this piece of code
due to `elements` being empty. Add a check for elements
being empty.