Added extensive handling of exceptions, moved shared code into a common file.