Working algorithm