Fix indexing bugs and add more comprehensive tests