Cleaned up logging, added some error handling.