main part of the rules algorithm