Flattens nested function, adds cost function asserts