Remove code duplication and manual indexing