improved key code logic