extracted the common code to a function.