better unflatten method