refactor the code to parse the rules in correct order, also made it easier to understand and extend