Initial implementation of flattening in code