Key handling refactoring

Not perfect, but it fixes bug and implements feature request.