Updated method flatten and added additional methods to rewrite