Replaced Util function expand with a more advanced one supporting nesting