fix NPE caused by Ctrl+D

Now Ctrl-D exits the program
add more checking