rewrote flattening algorithm, see IFlattenTree2