Adds more comprehensive exception handling, and general refactoring/cleanup.