Ported to javascript (not tested yet)