Refactor autocomplete code