major refactoring, changed error handling