Extracted some code to a function to improve readbility