Fixed some index boundary cases and added tests for them.