check buffer index is within range before using it (thanks to David Binderman)