Added flattening function