refactored autocomplete function