Simplified the algorithm