fixing bugs in the algorithm, still got some.