add comments, move code, and add some control for key events