Added flatten function