fix index bugs and refactor