Working algorithm 2