there's pretty much the same algorithm as is in C, but in Ruby