Implementing paper algorithm 1 one