Various refactorings for ViewSelector

Switched to using state machine, split logic into smaller methods.