extracted the commonly used code as a function to make code simple.