add exception handling and refactoring some fat functions