flatten implementation