Initial attempt at refactoring key handling logic