I have something similar, a Perl script which will collapse IPs and IP ranges into the smallest number of ranges.
I don't know if I explained it well enough for everyone (though I believe you understand :) ) so here's an example:
Have the range:
18.104.22.168/16 for example.
I have 2 IPs in this range I need to let through. Feed the range into the program as well as the IPs to exclude. It should spit out:
(my first excluded IP)
(my second excluded IP)
Obviously it would be more than 3 ranges, because I'm excluding single IPs instead of blocks which fit neatly into normal netmasks, but the above is the general idea.
I have them working pretty neatly in my Apache setup, but frankly I'm tired of it wasting resources even if its only to feed them 403 codes. I'd much rather have them eat NULL, lol.