More efficient approach to doing the rule match loop + some small code improvements