Condensed some repeated code into a function