Initial refactor of completion code.
First pass at flag-aware completion.