Better key handling

Fixes #939