flatten() utility function