moved function code out of if statement