More refactoring plus basic error handling