Added exception logging / handling and improved the code.