Refactor readline and keypress code