Generalize flatten tuples and remove some bugs