Modified code in last blog post to make input handling smarter