Large refactoring for input handling