Key processing moved out of main function