Unit-tested with tinytest and fixed bugs.