refactor autocomplete function