Changed speed and added bounds checking.