fixed several bugs in the algorithm