Changed the code to be more compact and readable and also to clear the input buffer.