refactor save function