Add flatten function and tests