Add tests, optimize code, fix timeout bug.