flatten/unflatten code + tests