Refactorized the materialize function, fixed tests