Added safety checks and key cleaning