implementing flatten