Working JS implementation. Bugs fixed.