It might be worth doing some performance timing of this function and its used of in_range() and gt(). They sound like good candidates to be inlined or become macros instead, since they could be used quite a lot. I'll do some of that after reviewing the code, but I was wondering if you have already.