simplified the algorithm