Work in progress on flattening
Working version
Bug fix