big refactoring, better handling of exceptions