flatten function replaced with a simpler version (more specific, as the general version was not working)