Flattened the structure and added error handling