Changed flatten implementation