better error checking and some code refactor like turning getkey into a function