Moved similar code snippets to a single function