Fix bugs in calculating indexes