Fixed flatten algorithm