Moved redundant code to function