Added some logging functionality and better error handling.