flatten function made recursive