Clean this up and make it handle exceptions a bit more sanely.