refactored to improve indexing logic