Added error handling and some clean-up