Updated flatten_with_extends function to account for lower-level extends