Specificity rules

These are the most important changes from #24 to fix specificity rules. As requested I have added test cases. I note that #25 also introduces some specificity logic, I believe the logic here is a bit more complete than in that pull request.