added a lot more error detection and ctrl-c handling