refactor: simpligy flattening algorithm