Moved logic to function