refactore save() function