Removed some duplicated code and placed it into a single function