better error handling, added shutdown hook