major refactoring: added error code checking and handling of exceptions