improved error handling; flattened code.