Refactored key handling