refactor finalize function