fixed bug in algorithm