Better api sorting

This adds sorting to the case API, which involved making the sorting utility code more general and correct.