Update flattening algorithm and clean up