fixed save function to handle references