Improved algortihm