Implement flatten algorithm.