improved flattening