Ported to ruby 1.8.6 plus bug tweaking