added algorithm 2 working version