I would suggest to wrap the following code to a separate function and which is better for adding unit tests.