improve an index check and add test cases.