algorithm by neil, function per Seno.Aiko@gmail.com, whatever's left of the patch is by me :) r=neil sr=neil