Refactor and optimize rules match check