Moved some duplicated logic into a function